简体   繁体   English

从另一个字符串创建一个字符串,在 C 中的每第 n 个字符后插入一个字符

[英]Create a string from another string with a character inserted after every nth character in C

I have a string:我有一个字符串:

012345678901234567890

I want it to broken into chunks of 7, like this:我希望它分成 7 个块,如下所示:

0123456-7890123-4567890

I wrote this code:我写了这段代码:

    strcpy(input,"01");
    strcat(input,"2345678901234567890");
    printf("input is %s\n",input);

    char *output = malloc(22 * sizeof(char));
    int i = 0;
    for (char* c = input; *c != '\0'; c++) {
        output[i] = *c;
        if (i > 0 && (i % 7 == 0)) {
            i++;
            output[i] = '-';

        }
        i++;
    }
    output[i] = '\0';
    printf("output is %s\n",output);

The output is this: output 是这样的:

input is 012345678901234567890
output is 01234567-890123-456789-0

The problem is complicated by the fact that the pointer is counted from zero.由于指针是从零开始计数的,所以问题变得复杂了。 Where is the error in my pointer logic?我的指针逻辑错误在哪里? How can make the code work for an arbitrary number of septets?如何使代码适用于任意数量的 septets?

EDIT编辑

Here is my solution.这是我的解决方案。 Is there a cleaner way?有没有更清洁的方法?

    char *input = (char*) malloc(22 * sizeof(char*));
    strcpy(input,"01");
    strcat(input,"2345678901234567890");
    printf("input is %s\n",input);

    int i = 0;
    int j = 0;
    char *output = malloc(22 * sizeof(char));
    for (char* c = input; *c != '\0'; c++) {
        output[i] = *c;
        j++;
        if (j % 7 == 0 && i <22) {

            i++;
            output[i] = '-';

            j = 0;
        }
        i++;
    }

For one thing, you are not allocating enough memory for the output .一方面,您没有为 output 分配足够的output You need to allocate room for 21 chars for copying chars from input , + 2 for the new dashes being inserted, + 1 for the null terminator.您需要为 21 个字符分配空间以从input复制字符,+ 2 用于插入的新破折号,+ 1 用于 null 终止符。 That is 24 chars needed, but you are allocating room for only 22 chars.这需要 24 个字符,但您只分配了 22 个字符的空间。

Also, you are using one variable i for two different purposes - indexing into input and indexing into output .此外,您将一个变量i用于两个不同的目的 - 索引到input和索引到output The insertion of the dashes will offset the indexing into output , which is the root problem with your code.插入破折号会将索引偏移到output ,这是您的代码的根本问题。 So you need to use two separate variables instead.因此,您需要改用两个单独的变量。

Try this:尝试这个:

char *input = malloc(22 * sizeof(char*));
strcpy(input, "01");
strcat(input, "2345678901234567890");
printf("input is %s\n", input);

int input_len = strlen(input);

char *output = malloc((input_len + ((input_len - 1) / 7) + 1) * sizeof(char));
int j = 0;
for (int i = 0; i < input_len; ++i) {
    if (i > 0 && i % 7 == 0) {
        output[j++] = '-';
    }
    output[j++] = input[i];
}
output[j] = '\0';
printf("output is %s\n", output);

Online Demo在线演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM