您的位置:首页 > 其它

编写一个函数,把一个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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: