用C語言實現字串反轉函式strrev的經典方法
字串反轉函式strrev不是C語言標準庫函式,很多C語言編譯器並沒有提供對它的支援,比如你在Linux下輸入Shell命令man 3 strlen,螢幕上會顯示,
- STRLEN(3) Linux Programmer's Manual STRLEN(3)
- NAME
- strlen - calculate the length of a string
- SYNOPSIS
- #include <string.h>
- size_t strlen(const char *s);
- DESCRIPTION
- The strlen() function calculates the length of the string s, excluding
- the terminating null byte ('\0').
- RETURN VALUE
- The strlen() function returns the number of characters in s.
- CONFORMING TO
- SVr4, 4.3BSD, C89, C99.
- SEE ALSO
- string(3), strnlen(3), wcslen(3), wcsnlen(3)
- COLOPHON
- This page is part of release 3.35 of the Linux man-pages project. A
- description of the project, and information about reporting bugs, can
- be found at http://man7.org/linux/man-pages/.
- GNU 2011-09-28 STRLEN(3)
告訴你strlen函式所實現的功能是calculate the length of a string,引用時需要#include <string.h>。而如果輸入man 3 strrev命令,Shell會告訴你,
- 在第 3 節中沒有關於 strrev 的手冊頁條目。
strrev函式不常用,不過在進行數制轉換和加密等場合還是有機會用到,因為一些針對嵌入式平臺的編譯器和VC對它提供了支援。對於不支援strrev函式的編譯器,許多網友提供了不少很有價值的解決方案,不過直接從VC所提供的原始碼中去提煉,似乎更能夠兼顧效率和移植性,以下提供一份經典的實現程式碼:
- char* strrev(char* s)
- {
- /* h指向s的頭部 */
- char* h = s;
- char* t = s;
- char ch;
- /* t指向s的尾部 */
- while(*t++){};
- t--; /* 與t++抵消 */
- t--; /* 回跳過結束符'\0' */
- /* 當h和t未重合時,交換它們所指向的字元 */
- while(h < t)
- {
- ch = *h;
- *h++ = *t; /* h向尾部移動 */
- *t-- = ch; /* t向頭部移動 */
- }
- return(s);
- }
===================================================================================
C++ STL中string的翻轉函式名是什麼(相當於C中的strrev(s))?
好像沒有,我一般是使用通用演算法中的reverse
std:;reverse(mystring.begin(), mystring.end());
template <class BidirectionalIterator>
void reverse(BidirectionalIterator first, BidirectionalIterator last);
Reverse reverses a range. That is: for every i such that 0 <= i <= (last - first) / 2), it exchanges *(first + i) and *(last - (i + 1)).
Defined in the standard header algorithm
#include <iostream>
#include <string>
using namespace std;
void main()
{
string s="123456";
reverse(s.begin(),s.end());
cout<<s;
}
//為什麼會在執行時出錯?
ADD:
#include <algorithm>
還是出錯!
用上了system(...),請再加上#include <cstdlib>
=======================================================================================
原 反轉字串(c++實現)
發表於3年前(2012-06-07 16:52) 閱讀(608) | 評論(0)1人收藏此文章,我要收藏 贊0 反轉字串?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#include <iostream>
using namespace
std;
void
reverse( char
*str, int len) //反轉函式,len指要反轉字串的長度
{
char *p=str,*q=str+len-1,temp;
//指標加法的單位是指標對應型別的位元組數,此處因為是char,所以即為1
while (*q== '\0' )
q--;
while (q>p)
{
temp=*p;
*p=*q;
*q=temp;
p++;
q--;
}
}
int
main()
{
char a=53;
cout<<a<<endl; //輸出的為ascii碼53位所代表的字元,即5
char str[11]=
"ackd12121" ; //從第四位至第十位全為空(\0),即字串結束標誌
cout<<str[5]; //輸出為空
cout<< sizeof (str)<<endl;
reverse(str, sizeof (str)-1); //sizeof為長度
cout<<str<<endl;
// cout<<'\n'<<endl; //反斜槓n為回車(換行) endl也為換行,並重新整理緩衝區
cout<< "換行結束" <<endl;
system ( "pause" );
return 0;
}
|