思路很重要:
获取字符串长度,两头交换相应字符。
核心代码:
1 void swap(char &x,char &y) 2 { 3 x = x^y; 4 y = x^y; 5 x = x^y; 6 } 7 void reverse(char *s) 8 { 9 int i = 0; 10 int len = strlen(s); 11 for(i = 0;i < len/2; ++i) 12 swap(s[i],s[len-i-1]); 13 }
示例代码:
1 #include <cstring> 2 #include <iostream> 3 using namespace std; 4 void swap(char &x,char &y) 5 { 6 x = x^y; 7 y = x^y; 8 x = x^y; 9 } 10 void reverse(char *s) 11 { 12 int i = 0; 13 int len = strlen(s); 14 for(i = 0;i < len/2; ++i) 15 swap(s[i],s[len-i-1]); 16 } 17 int main() 18 { 19 char str[20] = "hello,world"; 20 reverse(str); 21 cout<<str<<endl; 22 }