编写一个函数,把一个char组成的字符串循环右移n位
2015-07-10 15:17
441 查看
编写一个函数,把一个char组成的字符串循环右移n位
参考:/article/2697986.html例如:原来是”abcdefghi”,如果n = 2,移位后应该是”hiabcdefg”。
大体思路是这样的:
Step 1:将需要移动的字符串取出来,放入一个新的数组中Step 2:接着把前边没有移动的字符串 拼接到新的数组后边
Step 3:在新的字符串尾部添加一个字符串结束标志 ‘\0’
代码如下
[code]#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_LEN 1024 void loopMove1(char *srcStr, int moveSteps){ int length = strlen(srcStr) - moveSteps; char temp[MAX_LEN] = "\0"; strcpy(temp, srcStr+length); strcpy(temp+moveSteps, srcStr); // temp[strlen(srcStr)] = '\0'; *(temp+moveSteps+length) = '\0'; strcpy(srcStr, temp); } void loopMove2(char *srcStr, int moveSteps){ int length = strlen(srcStr) - moveSteps; char temp[MAX_LEN] = "\0"; //从srcStr字符串 的第length位开始拷贝,拷贝moveSteps个,拷贝到temp的起始位置 memcpy(temp, srcStr+length, moveSteps); memcpy(temp+moveSteps, srcStr, length); memcpy(srcStr, temp, length+moveSteps); } void loopMove3(char *srcStr, char *desStr, int moveSteps){ int length = strlen(srcStr)-moveSteps; strcpy(desStr, srcStr+length); strcpy(desStr+moveSteps, srcStr); desStr[strlen(srcStr)] = '\0'; } //这样写是为了 构成链式表达式 char *loopMove4(char *srcStr, char *desStr, int moveSteps){ int length = strlen(srcStr)-moveSteps; char *temp = desStr; strcpy(desStr, srcStr+length); strcpy(desStr+moveSteps, srcStr); desStr[strlen(srcStr)] = '\0'; return temp; } int main(void) { char str[10] = "abcdefghi"; int moveSteps = 2; loopMove1(str, moveSteps); printf("%s\n", str); loopMove2(str, moveSteps); printf("%s\n", str); char *resStr = (char *)malloc(strlen(str)+1); loopMove3(str, resStr, moveSteps); printf("%s\n", resStr); free(resStr); char inputStr[MAX_LEN] = "\0"; printf("input a string: \n"); scanf("%s", inputStr); char *resStr2 = (char *)malloc(strlen(inputStr)+1); loopMove3(inputStr, resStr2, moveSteps); printf("%s\n", resStr2); free(resStr2); char *resStr3 = (char *)malloc(strlen(inputStr)+1); printf("%s\n", loopMove4(inputStr, resStr3, moveSteps)); free(resStr3); return 0; }
相关文章推荐
- Android的MVP
- NSPredicate简单介绍
- UI编程-UIView及其⼦子类
- linux信号函数集(转载)
- Play 2.4 and Slick 3.0 Simple Example
- 提高 Vim 和 Shell 效率的 9 个建议
- 测试驱动开发TDD
- 黑马day16 jquery入门
- 机器学习技法总结(五)Adaptive Boosting, AdaBoost-Stump,决策树
- WCF技术剖析之二十五: 元数据(Metadata)架构体系全景展现[元数据描述篇]
- 关于Android Studio出现UNEXPECTED TOP-LEVEL EXCEPTION的错误
- selenium2入门 定位 窗体切换等等 (二)
- Winform ComboBox控件高亮显示
- WPF 魔方小游戏
- glusterfs分布式文件系统安装调试
- Java设计模式之访问者模式
- Java基础之IO流
- Android获取apk的版本及包名等信息
- 对freescale的mfgtool的ucl2.xml的理解
- Zigbee通讯漫谈(初次见面)