输入一个字符串和一个非负整数N,要求将字符串循环左移N次。
输入格式:
输入在第1行中给出一个不超过100个字符长度的、以回车结束的非空字符串;第2行给出非负整数N。
输出格式:
在一行中输出循环左移N次后的字符串。
输入样例:
Hello World!
2
输出样例:
llo World!He
思路:一次移动一位,共移动N次。
代码如下:
方法一:数组操作
#include <stdio.h>
#include <string.h>
int main(void){
char ch[101];
gets(ch); //读入字符串
int N;
scanf("%d",&N); //读入移动次数
char first;
int length = strlen(ch); //利用strlen函数求出字符串的长度
int i = 0;
while(N > 0){
first = ch[0]; //记录首位字符
while(i < length - 1){
ch[i] = ch[i+1]; //从第二个字符开始,向前移动一位
i++;
}
ch[i] = first; //注意:此时的i就是i+1,即最后一位
i = 0; //重置i
N--;
}
puts(ch);
return 0;
}
运行结果如下:
方法二:指针操作
代码如下:
#include <stdio.h>
int main(void){
char ch[101];
gets(ch); //读入字符串
int N;
scanf("%d",&N); //读入移动次数
char *p = ch,first;
while(N > 0){
first = ch[0]; //记录首位字符
while(*(p+1) != '\0'){
*p = *(p+1);
p++;
}
*p = first; //注意:此时的*p就是*(p+1),即最后一位
p = ch; //p指回首位字符
N--;
}
puts(ch);
return 0;
}
运行结果如下:
以上就是本道题的解法,水平一般,大家若有更好的解法欢迎分享在评论区哦!!!≧◉◡◉≦