這也是筆試中一道經典的C語言題: 給定一個字符串,將其翻轉。如abc ==> cba 拿到此題時,我是想都沒想,直接說,再用一個字符串tmp來緩存一下此串,然後一個for循環賦值搞定。 思路有了,代碼就有了。 [cpp] #include <stdio.h> #include <stdlib.h> int main() { char string[20],tmp[20]; int length; printf("please input less than 20 char:"); scanf("%s",string); printf("your input string is %s\n",string); length = strlen(string); printf("length is %d\n",length); for(int i = 0;i<length;++i) { tmp[i] = string[i]; } for(int i = 0;i<length;++i) { string[i] = tmp[length-i-1]; } printf("after revert:%s\n",string); return 0; } 用gcc編譯:gcc -o revert revert_string.c -std=c99 後運行,結果如我所料。但是我這個算法太不優雅了,因為將兩個字符數組賦值就用了一個循環,然後翻轉時再用一個循環,這效率真是不敢恭維。 優雅的方法應該是這樣的思路: 找到這個字符串的中間位置,然後將其左邊的字符與右邊的字符交換位置。 實現起來應該是下面這樣: [cpp] #include <stdio.h> #include <stdlib.h> int main() { char string[20], tmp; int length; printf("please input less than 20 char:"); scanf("%s",string); printf("your input string is %s\n",string); //get string length,very useful method for(length=0;string[length];length++) ; printf("length is %d\n",length); //very beateful !!! for(int i=0;i<length/2;i++) { tmp = string[i]; printf("tmp is %c\n" ,string[i]); string[i] = string[length-i-1]; printf("string[%d] is %c\n",i,string[length-i-1]); string[length-i-1] = tmp; printf("string[%d] is %c\n",length-i-1,tmp); } printf("after revert:%s\n",string); return 0; } 運行效果如下: [plain] D:\workspace\C\revert_string>gcc -o revert revert_string.c -std=c99 D:\workspace\C\revert_string>revert please input less than 20 char:abc your input string is abc length is 3 tmp is a string[0] is c string[2] is a after revert:cba D:\workspace\C\revert_string>revert please input less than 20 char:abcd your input string is abcd length is 4 tmp is a string[0] is d string[3] is a tmp is b string[1] is c string[2] is b after revert:dcba 這樣的算法,相比之前要提高甚多效率。只要開動腦筋,世界會更加優雅。