循环右移

编写一个函数,把一个char组成的字符串循环右移n位。

编写一个函数,把一个char组成的字符串循环右移n位。例如,原来是“abcdefghi”,如果 n=2,移位后应该是“hiabcdefgh”。


函数原型如下:
   
   
  1. //pStr是指向以'\0'结尾的字符串的指针
  2. //steps是要求移动的n位
  3. void LoopMove(char * pStr, int steps);

题目分析

这个题目主要考查读者对标准库函数的熟练程度,在需要的时候,引用库函数可以很大程度上简化程序编写的工作量。

最频繁被使用的库函数包括strcpy()、memcpy()和memset()。

以下采用两种方法来解答。

方法一代码:
   
   
  1. #include <stdio.h>
  2. #include <string.h>
  3. #define MAX_LEN 100
  4. void LoopMove(char *pStr, int steps){
  5. int n = strlen(pStr) - steps;
  6. char tmp[MAX_LEN];
  7. memcpy(tmp, pStr+n, steps); //拷贝字符串
  8. memcpy(pStr+steps, pStr, n);
  9. memcpy(pStr, tmp, steps); //合并得到结果
  10. }
  11. int main(){
  12. char str[] = "www.coderbbs.com";
  13. LoopMove(str, 3);
  14. printf("%s\n", str);
  15. return 0;
  16. }

方法二代码:
   
   
  1. #include <stdio.h>
  2. #include <string.h>
  3. #define MAX_LEN 100
  4. void LoopMove(char *pStr, int steps){
  5. int n = strlen(pStr) - steps;
  6. char tmp[MAX_LEN];
  7. strcpy(tmp, pStr+n); //拷贝字符串
  8. strcpy(tmp+steps, pStr);
  9. *(tmp + strlen(pStr)) = '\0';
  10. strcpy(pStr, tmp); //合并得到结果
  11. }
  12. int main(){
  13. char str[] = "www.coderbbs.com";
  14. LoopMove(str, 3);
  15. printf("%s\n", str);
  16. return 0;
  17. }
输出结果:
comwww.coderbbs.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值