c语言字母循环移位,【C语言】字符串右循环移位

请实现字符串右循环移位函数,比如:“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,这里不再提供代码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值