分享

用C语言编写一个函数,把一个字符串循环右移n位

 心不留意外尘 2016-07-30

http://c./cpp/html/2803.html
2015
编写一个函数,把一个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

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多