This is also a classic C language in the written test:
Given a string, flip it. For example, abc => CBA
When I got this question, I didn't even think about it. Simply put, I used a string tmp to cache this string and then assigned a value for a for loop.
The code will be available if you have ideas.
#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;}
Compile with gcc: gcc-o revert revert_string.c-std = c99
And the result is as expected. However, my algorithm is not elegant, because I use a loop to assign values to two character arrays and then use a loop to flip the array. This efficiency is not flattering.
The elegant method should be like this:
Find the middle position of the string, and then swap the character on the left with the character on the right.
The implementation should be as follows:
#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 methodfor(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;}
The running effect is as follows:
D:\workspace\C\revert_string>gcc -o revert revert_string.c -std=c99D:\workspace\C\revert_string>revertplease input less than 20 char:abcyour input string is abclength is 3tmp is astring[0] is cstring[2] is aafter revert:cbaD:\workspace\C\revert_string>revertplease input less than 20 char:abcdyour input string is abcdlength is 4tmp is astring[0] is dstring[3] is atmp is bstring[1] is cstring[2] is bafter revert:dcba
This algorithm is much more efficient than before. As long as you use your brains, the world will become more elegant.