逆置字符串
1.输入字符串
char ch[]=""; gets(ch);
这里没有使用scanf(),因为当遇到空格时,scanf()就会停止。
而此字符串中存在空格
使用gets()就可以巧妙地避免这一问题
2.逆置
1.逆置整个字符串 reverse(char* left, char* right) { while (left < right) { char tmp = *left; *left = *right; *right = tmp; left++; right--; } } 2.逆置每个单词 char* start = ch; while (*start) { char* end = start; //当*end==''时,前面为假,不进入循环 //当*end==‘\0'时,前面为真,后面为假,不进入循环 while (*end != ' ' && *end != '\0') { end++; } reverse(start, end - 1); //当end指向字符串结尾处的'\0'将不再向后移动 if (*end != '\0') { end++; } start = end; }
3.输出
printf("%s\n",ch);
完整代码
#include<stdio.h> #include<string.h> #include<assert.h> void reverse(char* left, char* right) { assert(left); assert(right); while (left < right) { char tmp = *left; *left = *right; *right = tmp; left++; right--; } } int main() { char ch[] = " "; gets(ch); int len = strlen(ch); reverse(ch, ch + len - 1); char* start = ch; while (*start) { char* end = start; //当*end==''时,前面为假,不进入循环 //当*end==‘\0'时,前面为真,后面为假,不进入循环 while (*end != ' ' && *end != '\0') { end++; } reverse(start, end - 1); //当end指向字符串结尾处的'\0'将不再向后移动 if (*end != '\0') { end++; } start = end; } printf("%s\n", ch); return 0; }