打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

http://c.biancheng.net/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.
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
【编程练习】字符串循环右移
作用是把一个char组成的字符串循环右移n个
字符串移位:如“abcdefghi”右移2位后变成“cdefghiab”
LoopMove
可以通过函数strncat strcat实现从字符加入到字符串中
经典C/C++算法
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服