反转字符串
Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters, including the null character.)
SOLUTION
The only "gotcha" is to try to do it in place, and to be careful for the null character.
1 #include <stdio.h> 2 void reverse(char *str){ 3 char *end = str; 4 char tmp; 5 if(str) { 6 while(*end){ 7 ++end; 8 } 9 --end; 10 while(str < end) { 11 tmp = *str; 12 *str++ = *end; 13 *end-- = tmp; 14 } 15 } 16 } 17 18 int main() { 19 char s[] = "abcdef";//不要写成char *s = "abcdef";因为s指向字符串常量,不能改变字符串常量的值 20 printf("%s\n",s); 21 reverse(s); 22 printf("%s\n",s); 23 return 0; 24 }
浙公网安备 33010602011771号