这也是笔试中一道经典的C语言题:
给定一个字符串,将其翻转。如abc ==> cba
拿到此题时,我是想都没想,直接说,再用一个字符串tmp来缓存一下此串,然后一个for循环赋值搞定。
思路有了,代码就有了。
#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
后运行,结果如我所料。但是我这个算法太不优雅了,因为将两个字符数组赋值就用了一个循环,然后翻转时再用一个循环,这效率真是不敢恭维。
优雅的方法应该是这样的思路:
找到这个字符串的中间位置,然后将其左边的字符与右边的字符交换位置。
实现起来应该是下面这样:
#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; }运行效果如下:
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