c - 定位和替换一个子串(C语言)

标签 c string

<分区>

我编写了以下代码,目的是在字符串上使用指针算法来查找和替换目标子字符串。显然,它并不优雅,但不幸的是它也是不正确的——它向字符串中添加了无关的字符。

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

int main() {
    char string[] = "The quick brown fox jumped over the lazy dog.";
    char target[] = "brown"
    char replacement[] = "ochre";
    char segment[80+1];
    char pre_segment[80+1];
    char post_segment[80+1];
    int S = strlen(string), T = strlen(target);
    for (int i = 0; i < S; i++) {
        strncpy(segment, string + i, T);
        if (strcmp(segment, target) == 0) {
        >>> strncpy(pre_segment, string, i); <<<
            strncpy(post_segment, string + i + T,
                S - (i + T));
            strcat(pre_segment, replacement);
            strcat(pre_segment, post_segment);
            printf("%s\n", pre_segment);
        }
    }
    return 0; 
}

在标记为 >>>this<<< 的行之后,在替换与 pre_segment 连接之前,已将无关字符添加到替换之前。

有人可以给我关于如何调试的建议吗? (也欢迎提出更好的解决方案的建议,但请尽量明确。另外,我不应该为此使用动态内存分配。)

最佳答案

不要使用strncpy。它几乎肯定不会像您认为的那样工作。特别是,它不保证 NUL 终止,同时愚弄人们认为它确实如此。如果您想精确复制 n 个字符,请使用 memcpy(dest, src, n); 然后使用 dest[n] = '\0';。缺少 NUL 终止可能会导致您的问题。 (在你的调试器中检查!)

但是,根本不需要执行strncpy。使用 strncmpmemcmp。 (仅当您知道字符串中至少有 strlen(target) 个字节时才使用 memcmp。)如果 strlen(target) 个字节从 string 中的某个点开始匹配 target,然后您就找到了匹配项。

更好的方法是使用 strstr 来查找字符串的下一次出现。

关于c - 定位和替换一个子串(C语言),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44687473/

相关文章:

string - 比较字符串的最后一个字符

swift - 对成员 "text"的模糊引用

algorithm - 字符串列表中的字符

android - 如何将一个字符串拆分成几个字符 block ?

C:包含动态分配成员的结构的范围?

python - 如何在 C 程序中运行 Python 可执行文件(.py)(例如使用 execvp)?

php - 快速CGI, SCGI,

regex - PowerShell:输出正则表达式而不是结果

C中的字符函数不输出任何内容

C 到 MIPS 转换