字符串左旋
题目:有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数。
思路:先把这个字符串的前半部分保存到一个新的字符串中,再把后半部分保存到另一个字符串中。最后,拼接这两个字符串。
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 | void Get_Front(char* ch,int input,int length,char* Front)//获得前半部分{ int i=0; for (i=0; i<input; i++) { Front[i] = ch[i]; }}void Get_Behind(char* ch,int input,int length,char* Behind)//获得后半部分{ int j = 0; int i=0; for (i=input; i<length; i++) { Behind[j] = ch[i]; j++; }}void Left(char* ch,int input){ int length = 0;//字符串长度 int x = 0; while (ch[length] != '\0')//先看看ch里存了几个字符 { length++; } char Front[100];//先定义一个字符串来存前边的字符串 char Behind[100];//定义一个字符串存后半部分字符串 Get_Front(ch,input,length,Front);//把前半部分存到Front里 Get_Behind(ch,input,length,Behind);//把后半部分存到Behind里 int i = 0; for (i=0; i<length-input; i++) //替换 { ch[i] = Behind[i]; } for (i=length-input; i<length; i++)//替换 { ch[length-input+x] = Front[x]; x++; }}int main() { char ch[100] = {0}; int input = 0; printf("请输入字符串:->"); scanf("%s",ch); printf("请输入要左旋几个字符:->"); scanf("%d",&input); Left(ch,input); printf("%s\n",ch); return 0;} |
思路:先把这个字符串的后边的字符串保存到一个新的临时字符串中,再把后边的字符往前移,最后把新字符串接到后面。
123456789101112131415161718192021222324252627282930313233343536 | void Left(char* ch,int input){ int i = 0; char temp[input]; int length = 0; while (ch[length] != '\0')//看一下输入的字符串长度是多少 { length++; } for (i=0; i<input; i++)//先把要后移的字符串保存到一个临时字符串中 { temp[i] = ch[i]; } for (i=input; i<length; i++)//把后边要前移的字符串移动一下 { ch[i-input] = ch[i]; } for (i=0; i<input; i++) //把之前保存的临时字符串赋值到原数组的最后 { ch[length-input+i] = temp[i]; }} int main(){ char ch[100] = {0}; int input = 0; printf("请输入字符串:->"); scanf("%s",ch); printf("请输入要左旋几个字符:->"); scanf("%d",&input); Left(ch,input); printf("%s\n",ch); return 0;} |
字符串右旋
12345678910111213141516171819202122232425262728293031323334353637 | void Right(char* ch,int input){ int i = 0; char temp[input]; int length = 0; int x = 0; while (ch[length] != '\0')//看一下输入的字符串长度是多少 { length++; } for (i=length-input; i<length; i++)//先把要前移的字符串保存到一个临时字符串中 { temp[x] = ch[i]; x++; } for (i=length-input; i>=0; i--)//把前边的字符串往后移,给临时字符串挪位置 { ch[i+input-1] = ch[i-1]; } for (i=0; i<input; i++)//把之前保存的临时字符串赋值到原数组的最前边 { ch[i] = temp[i]; }}int main(){ char ch[100] = {0}; int input = 0; printf("请输入字符串:->"); scanf("%s",ch); printf("请输入要右旋几个字符:->"); scanf("%d",&input); Right(ch,input); printf("%s\n",ch); return 0;} |