用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>
=======================================================================================
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;
}
|