C - 如何重新排列字符串

时间:2014-05-29 12:46:18

标签: c

我有一个命令行参数,它是字母数字,例如" ABCDE1234567"以argv [1]传递。我正在重新排列char *,因此前4个字符被发送到字符串的末尾,所以它最终会像E1234567ABCD一样。

我从argv获取char *如下:

char* input = argv[1];
validate(input);

然后传递给一个函数来完成工作,

void validate (char* input) {
    // move the first 4 chars to the end
    // this is where i'm stuck :-)
}

我知道这应该很简单,但我一直在尝试使用strcpy,sprintf,for循环,但却没有到达任何地方。

编辑:

我尝试将没有前四个字符的字符串复制到缓冲区中,但这似乎没有产生任何结果:

int n = strlen(input);
char buffer [n - 4];

for (int i = 4; i <= n; i++) {
    printf("%c\n", input[i]);
    sprintf(buffer, "%c", input[i]);
}
printf("%s\n", buffer);

3 个答案:

答案 0 :(得分:2)

考虑另一种方法:如果将两个字符串连接在一起会发生什么:

ABCDE1234567 ABCDE1234567

...然后移动一个&#34;滑动窗口&#34;一些性格前锋:

ABCD E1234567ABCD E1234567

您可以使用指向正确位置的指针轻松实现此目的,并将所需数据复制到目标位置。

请注意,字符串是一个字符数组,后跟一个空字符\ 0。字符串只是一个字符数组。

答案 1 :(得分:2)

字符串函数的组合可能是最简单的选择:

#include <stdio.h>
#include <string.h>

void validate (char* input) {
    // Temp storage for four characters being moved.

    char four[4];

    // Get length but do nothing unless long enough.

    size_t len = strlen (input);
    if (len < 5)
        return;

    // Save first four characters.

    memcpy (four, input, 4);

    // Move the others (need memmove for overlapping regions).
    // input is address of first character.
    // &(input[n-1]) is address of nth character.

    memmove (input, &(input[4]), len - 4);

    // Put saved four characters at the end.
    // &(input[len - n]) is address of nth-last character.

    memcpy (&(input[len - 4]), four, 4);
}

// A simple test program for checking.

int main (int argc, char *argv[]) {
    if (argc < 2) {
        printf ("Not enough arguments\n");
        return 1;
    }
    printf ("Converted '%s' ", argv[1]);
    validate (argv[1]);
    printf ("to '%s'\n", argv[1]);
    return 0;
}

答案 2 :(得分:0)

下面的代码可能有帮助。

void validate (char* input) {
        char temp[10];
        strncpy ( temp, input, 4 ); //copy first 4 chars to temp
        temp = '\0'; //terminate it.

        //Copy characters from 5th to end
        for(i=0;i<strlen(input)-4;i++)
         {
           input[i] = input[i+4];
         }
         //copy remaining four characters from temp at last
         for(i=strlen(input)-4,j=0;i<strlen(input);i++)
         {
           input[i]=temp[j];
           j++;
         }

}