编写的函数能把一个char组成的字符串循环右移n个。例如原来是“abcdefghi”,如果n = 2,移位后应该是“hiabcdefg”.
代码
#include <stdio.h>
#include <stdlib.h>
void loopMove(char *str,int n)
{
int i = 0;
char * temp = NULL:
int strLen = 0;
char * head = str;
while(*str++);
strLen = str-head-1;
n = n%strLen;
temp = (char*)malloc(n);
for(i = 0;i<n;i++)
{
temp[i] = head[strLen - n +i];
}
for(i = strLen-1;i>=n;i--)
{
head[i] = head[i=n];
}
for(i = 0;i<n;i++)
{
head[i] = temp[i];
}
free(temp);
}
int main()
{
char string[] = "123456789";
int steps = 0;
printf("%s\n",string);
scanf("%d",&steps);
loopMove(string,steps);
printf("%s\n",string);
return 0;
}