文章时效性提示
本文发布于 495 天前,部分信息可能已经改变,请注意甄别。
字符串左旋
题目:有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数。
思路:先把这个字符串的前半部分保存到一个新的字符串中,再把后半部分保存到另一个字符串中。最后,拼接这两个字符串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| #include <stdio.h> 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') { length++; } char Front[100]; char Behind[100]; Get_Front(ch,input,length,Front); Get_Behind(ch,input,length,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; }
|
思路:先把这个字符串的后边的字符串保存到一个新的临时字符串中,再把后边的字符往前移,最后把新字符串接到后面。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| #include <stdio.h> 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; }
|
字符串右旋
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| #include <stdio.h> 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; }
|