/*Write code to reverse a C-Style String.(C-String means that "abcd" is represented as five characters, including the null charater.)*/
#include <iostream>
#include <string>
using namespace std;
void swap(char &a, char &b)
{
char temp;
temp = a;
a = b;
b = temp;
}
void reverse(char* str)
{
if(!str) return;
char *p=str, *q=str;
while(*q) q++;
--q;
while(p<q)
swap(*p++, *q--);
}
int main()
{
char str[] = "abcdefg";
reverse(str);
cout << "str = abcdefg" << " && reversed str = " << str << endl;
return 0;
}
swap的其他方法
void swap1(char &a, char &b)
{
a=a^b;
b=a^b;
a=a^b;
}
reverse的其他方法
void reverse1(char *str)
{
if(!str) return;
int len=strlen(str);
for(int i=0; i<len/2; ++i)
{
swap1(str[i],str[len-1-i]);
}
}
本文介绍了一种使用C语言风格实现字符串反转的方法,并提供了两种不同的实现方式:一种是通过逐个字符交换,另一种是利用异或操作进行字符交换。此外,还展示了如何使用这些函数来反转一个实际的字符串。

被折叠的 条评论
为什么被折叠?



