题目
- Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters, including the null character.)
- 写代码翻转一个C风格的字符串。(C风格的意思是”abcd”需要用5个字符来表示,包含末尾的结束字符)
思路
- 以”abcd”为例,先找到末尾的结束字符’\0’,再找到结束符前向前的字符’d’与从头开始向后的字符’a’进行交换,直到依次翻转完毕。
- 直接查整个字符串的长度(strlen)n,将第i个与第n-i-1个字符进行交换。
- 其中2.也可以用string直接完成,这里注意在printf()时,因为string不是内置类型,需要写成s.c_str()。
代码
#include <iostream>
#include <cstring>
using namespace std;
void swap(char &a, char &b){
a = a^b;
b = a^b;
a = a^b;
}
void reverse1(char *s){
if(!s) return;
char *p = s, *q = s;
while(*++q) {
}
q--;
while(p < q) {
swap(*p++, *q--);
}
}
void reverse2(char *s){
int n = strlen(s);
for(int i = 0; i < n/2; i++) {
swap(s[i], s[n-i-1]);
}
}
void reverse3(string &s){
int n = s.length();
for(int i = 0; i < n/2; i++) {
swap(s[i], s[n-i-1]);
}
}
int main(){
char s[] = "123456789";
reverse1(s);
//reverse2(s);
printf("%s\n", s);
string s1 = "123456789";
reverse3(s1);
printf("%s\n", s1.c_str());
return 0;
}