繁体   English   中英

C - 替换字符串中的子字符串

[英]C - Replace substring in string

作为我学习 CI 过程的一部分,我正在开发一些用于字符串操作的函数。 其中之一具有替换字符串中的子字符串的功能,并提出了一些问题。 我在 C99 工作; 在 Mac OS Sierra 和 FreeBSD 上编译。

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

char *repstr(char input[], char rep[], char new[]) {

    char *output = malloc(strlen(input)*5); // <- Question 2
    int replen = strlen(rep);
    int newlen = strlen(new);
    int a, b, c = 0;

    // printf("input: %ld\t%s\n", strlen(input), input); // <- Question 1

    while(input[a]) {
            if(input[(a+b)] == rep[b]) {
                    if(b == replen - 1) {
                            strcat(output, new);
                            a += replen;
                            c += newlen;
                            b=0;
                    }
                    else b++;
            } else {
                    output[c] = input[a];
                    a++;
                    c++;
            }
    }

    return output;
}


int main() {

    char buffer[] = "This is the test string test string test test string!";
    char rep[] = "test";
    char new[] = "tested";

    int len = strlen(buffer);

    char output[len+5];

    printf("input: %d\t%s\n", len, buffer); // <- Question 1
    strcpy(output, repstr(buffer, rep, new));
    printf("output: %ld\t%s\n", strlen(output), output);

    return 0;
}

问题 1:在 main() 中执行此行时会导致段错误。 但是,在函数内执行时,一切似乎都正常。 为什么?

问题 2:我意识到我需要为输出分配相当大的内存块才能看起来像预期的那样。 strlen(input)*5 是一个似乎有效的任意数字,但为什么在降低数字时会出现看似“随机”的错误?

注意! 由于这是我在 CI 中学习编码过程的一部分,因此我主要不是对(更有效的)预制解决方案感兴趣以解决问题(已经有了它们),而是解释列出的两个问题 - 这样我就可以解决问题自己的问题。

还; 这是我在 SO 论坛上的第一篇文章。 你好。

问题 1:在 main() 中执行此行时会导致段错误。 但是,在函数内执行时,一切似乎都正常。 为什么?

不, printf("input: %d\\t%s\\n", len, buffer); // <- Question 1 printf("input: %d\\t%s\\n", len, buffer); // <- Question 1不是导致段错误的原因。

printf("output: %ld\t%s\n", strlen(output), output);

这部分是, strlen不返回int但它返回size_t 如评论中所述,使用%zu将其打印出来。

此外, while(input[a])将在 NULL 终止符处停止,这意味着您的output将永远不会包含终止符,因此printf将继续读取,您应该在最后添加它:

output[c] = '\0';

此外,正如@LPs 在评论中所指出的,您应该将使用的变量初始化为零:

 int a = 0, b = 0, c = 0;

问题 2:我意识到我需要为输出分配相当大的内存块才能看起来像预期的那样。 strlen(input)*5 是一个似乎有效的任意数字,但为什么在降低数字时会出现看似“随机”的错误?

可能是因为你没有分配足够的内存。 由于字符串长度取决于运行时因素,因此无法知道您应该分配所需的最大数量所需的确切内存:

char *output = malloc(strlen(input) * strlen(new) + 1);

暂无
暂无

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

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