编写一个函数,把一个char组成的字符串循环右移n位。
编写一个函数,把一个char组成的字符串循环右移n位。例如,原来是“abcdefghi”,如果 n=2,移位后应该是“hiabcdefgh”。
函数原型如下:
最频繁被使用的库函数包括strcpy()、memcpy()和memset()。
以下采用两种方法来解答。
方法一代码:
方法二代码:
输出结果:
编写一个函数,把一个char组成的字符串循环右移n位。例如,原来是“abcdefghi”,如果 n=2,移位后应该是“hiabcdefgh”。
函数原型如下:
- //pStr是指向以'\0'结尾的字符串的指针
- //steps是要求移动的n位
- void LoopMove(char * pStr, int steps);
题目分析
这个题目主要考查读者对标准库函数的熟练程度,在需要的时候,引用库函数可以很大程度上简化程序编写的工作量。最频繁被使用的库函数包括strcpy()、memcpy()和memset()。
以下采用两种方法来解答。
方法一代码:
- #include <stdio.h>
- #include <string.h>
- #define MAX_LEN 100
- void LoopMove(char *pStr, int steps){
- int n = strlen(pStr) - steps;
- char tmp[MAX_LEN];
- memcpy(tmp, pStr+n, steps); //拷贝字符串
- memcpy(pStr+steps, pStr, n);
- memcpy(pStr, tmp, steps); //合并得到结果
- }
- int main(){
- char str[] = "www.coderbbs.com";
- LoopMove(str, 3);
- printf("%s\n", str);
- return 0;
- }
方法二代码:
- #include <stdio.h>
- #include <string.h>
- #define MAX_LEN 100
- void LoopMove(char *pStr, int steps){
- int n = strlen(pStr) - steps;
- char tmp[MAX_LEN];
- strcpy(tmp, pStr+n); //拷贝字符串
- strcpy(tmp+steps, pStr);
- *(tmp + strlen(pStr)) = '\0';
- strcpy(pStr, tmp); //合并得到结果
- }
- int main(){
- char str[] = "www.coderbbs.com";
- LoopMove(str, 3);
- printf("%s\n", str);
- return 0;
- }
comwww.coderbbs.