请实现字符串右循环移位函数,比如:“abcdefghi”循环右移2位就是“hiabcdefg”.
函数原型:void RightLoopMove(char *pStr, unsignedshort steps)
函数参数说明:
pStr: Point to a ‘\0’ terminated string
steps: The rotate shift numbers
#include#include#include#includevoid RightLoopMove(char *pStr, unsigned short steps)
{
assert(pStr);
char *str=NULL;
int i = 0;
char *start = pStr;
int len=strlen(pStr);
str = (char*)malloc(sizeof(steps + 1));
if (str == NULL)
{
printf("out of memery\n");
return;
}
for (i = 0; i < steps; i++) //将右移的部分存放进str里
{
*str++ = *(start+len -steps+ i );
}
for (i = len - steps; i>0;i--) //剩余的部分向后移steps位
{
*(start + steps+i - 1) = *(start + i - 1);
}
for (i = 0; i < steps; i++) //将str的内容放到字符串前面腾出的位
{
*(start + steps - i - 1) = *(--str);
}
free(str);
str = NULL;
}
int main()
{
char arr[] = "abcdefghi";
RightLoopMove(arr, 2); //测试右移两位
printf("%s", arr);
getchar();
return 0;
}第二种方法,主要用了库函数
#define _CRT_SECURE_NO_WARNINGS 1
#include#include#include#include#define MAX_LEN 20
void RightLoopMove(char *pStr, unsigned short steps)
{
assert(pStr);
char arr[MAX_LEN] = { 0 };
int n = strlen(pStr)-steps;
strcpy(arr,pStr+n); //需要移位的字符拷给arr
strcpy(arr + steps, pStr); //再把剩下的字符拷给arr
*(arr + strlen(pStr)) = '\0'; //上一步会多拷steps个字符,加\0的同时也解决了这个问题。
strcpy(pStr, arr); //arr里的字符拷给源串
}
int main()
{
char arr[] = "abcdefghi";
RightLoopMove(arr, 2); //测试右移两位
printf("%s", arr);
getchar();
return 0;
}
可以用strcpy意味着此处也可以用memcpy,这里不再提供代码。