【问题标题】:Replacing a whole word and not substrings in a string in C替换整个单词而不是C中字符串中的子字符串
【发布时间】:2019-02-27 20:36:01
【问题描述】:

我正在尝试替换 C 字符数组中的整个单词并跳过子字符串。我进行了研究,最终得到了非常艰难的解决方案,而我认为如果有人可以帮助我,我会有更好的主意。 假设我有字符串:

char sentence[100]= "apple tree house";

我想用数字 12 替换树:

"apple 12 house"

我知道单词是用空格分隔的,所以我的想法是:

1.用分隔符空格标记字符串
2. 在 while 循环中,使用库函数 STRCMP 检查字符串是否等于令牌以及是否要替换它。

当我尝试替换字符串时,我遇到了问题,因为我无法做到。

void wordreplace(char string[], char search[], char replace[]) {

  // Tokenize
  char * token = strtok(string, " ");

  while (token != NULL) {
    if (strcmp(search, token) == 0) {
      REPLACE SEARCH STRING WITH REPLACE STRING
    }
    token = strtok(NULL, " ");
  }
  printf("Sentence : %s", string);

}

有什么我可以使用的建议吗?我想这可能真的很简单,但我是初学者,非常感谢 :)
[编辑]:空格是唯一的分隔符,通常要替换的字符串不会比原来的长。

【问题讨论】:

  • 与这个问题的算法方面密不可分的挑战之一是内存管理问题。 C 迫使您经常担心这一点,例如,如果替换单词会使字符串比原来的更长怎么办?你会超出调用者给你的分配内存吗?你知道你有多少吗?如果您需要编辑给定的相同字符串,您可能只能在所有情况下通过分配一个临时字符串来完成。您没有在输入周围说明任何特定参数 - 例如空格是唯一重要的空格吗?
  • @BenZotto 空格是唯一的分隔符并且要替换的字符串不比原来的长
  • 在您的编辑中,您说字符串不比原始字符串长。然而,在你用“香蕉”替换“树”的例子中。新字符串比原始字符串长两个字符。如果输入是“tree tree tree”,它将长六个字符。即,结果输出的大小发生不可预测的变化,这是一个有用的数据点供您使用。它告诉你,如果没有关于分配的字符串大小的进一步上下文,这个函数本身就无法真正工作。
  • 很抱歉是我的错我编辑了它:) 谢谢你提到它
  • 嗯,好的。如果您只是缩小输入长度,而不是扩展它,那么函数的可能性和简单程度就会有很大的不同。

标签: c string replace word


【解决方案1】:

在这种情况下我会避免strtok(因为它会修改字符串作为对其进行标记的副作用),并通过基本上逐个字符查看字符串并保持“读取”和“写”索引。因为输出永远不会比输入长,所以写入索引永远不会领先于读取索引,您可以“回写”并在同一字符串内进行更改。

为了可视化这一点,我发现在框中写出输入并为当前读写索引绘制箭头并跟踪整个过程很有用,这样您就可以验证您的系统是否可以执行您希望它执行的操作并且你的循环和索引都像你期望的那样工作。

这是一个与我自己的想法倾向于处理这种算法的方式相匹配的实现。它遍历字符串并向前看以尝试从当前字符进行匹配。如果找到匹配项,它将替换复制到当前位置,并相应地增加两个索引。

void wordreplace(char * string, const char * search, const char * replace) {

    // This is required to be true since we're going to do the replace
    // in-place:
    assert(strlen(replace) <= strlen(search)); 

    // Get ourselves set up
    int r = 0, w = 0; 
    int str_len = strlen(string);
    int search_len = strlen(search);
    int replace_len = strlen(replace);

    // Walk through the input character by character.
    while (r < str_len) {

        // Is this character the start of a matching token? It is
        // if we see the search string followed by a space or end of
        // string. 
        if (strncmp(&string[r], search, search_len) == 0 &&
            (string[r+search_len] == ' ' || string[r+search_len] == '\0')) { 

            // We matched the search token. Copy the replace token.
            memcpy(&string[w], replace, replace_len);

            // Update our indexes.
            w += replace_len;
            r += search_len;
        } else {
            // Otherwise just copy this character.
            string[w++] = string[r++];
        }
    }

    // Be sure to terminate the final version of the string.
    string[w] = '\0';
}

(请注意,我调整了您的函数签名以使用更惯用的指针表示法而不是 char 数组,并且根据下面流感的评论,我将搜索和替换标记标记为“const”,这是函数宣传它的一种方式不会修改这些字符串。)

【讨论】:

  • search 和 replace 应该是 const char *
  • 另一个小建议:将strcpy替换为memcpy,以避免不必要的空字符插入。
  • 这似乎与长度等于或大于搜索词的替换词有关。
  • @flu:谢谢,这不仅是不必要的,而且在某些情况下也是不正确的。固定。
  • @DavidC.Rankin 谢谢,仅供参考,根据 OP 在 cmets(和编辑)中的澄清,更长的情况实际上并不是(我认为?)这里的问题空间的一部分。同意它打开一个完整的其他算法的蠕虫,如果它是这种方法是不够的,至少没有创建一个额外的临时缓冲区......一些不可知的长度。
【解决方案2】:

做你想做的事变得有点复杂,因为你需要处理以下场景:

  1. 替换比原版短 -- 因此您需要移动剩余的行以跟随替换文本以避免留下空白;
  2. replacement is same length as original -- 普通情况,用替换覆盖原来的;最后
  3. replacement is long than original -- 您必须验证原始字符串加上替换长度差异仍然适合原始字符串的存储,您必须将行尾复制到临时在进行替换之前先缓冲,然后将临时缓冲区中的其余行添加到末尾。

strtok 在这里有一些缺点,因为它在标记化过程中会更改原始字符串。 (您可以只制作一个副本,但如果您想要就地替换,则需要进一步查看)。 strstr 和 strcspn 的组合允许您在原始字符串中查找特定搜索字符串时以更有效的方式对原始字符串进行操作。

strcspn 可以像 strtok 一样使用一组分隔符来提供找到的当前令牌的长度(以确保 strstr 不匹配您的搜索词作为 lesser-included-substring 一个更长的单词,比如trees 中的tree)然后它变成了一个简单的问题,用strstr 循环并用strcspn 验证令牌的长度,然后只应用三种情况之一以上。

一个包含内嵌 cmets 以帮助您跟进的简短示例实现可能是:

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

#define MAXLIN 100

void wordreplace (char *str, const char *srch,
                    const char *repl, const char *delim)
{
    char *p = str;                      /* pointer to str */
    size_t  lenword,                    /* length of word found */
            lenstr = strlen (str),      /* length of total string */
            lensrch = strlen (srch),    /* length of search word */
            lenrepl = strlen (repl);    /* length of replace word */

    while ((p = strstr (p, srch))) {    /* srch exist in rest of string? */
            lenword = strcspn (p, delim);   /* get length of word found */
        if (lenword == lensrch) {       /* word len match search len */
            if (lenrepl == lensrch)     /* if replace is same len */
                memcpy (p, repl, lenrepl);  /* just copy over */
            else if (lenrepl > lensrch) {   /* if replace is longer */
                /* check that additional lenght will fit in str */
                if (lenstr + lenrepl - lensrch > MAXLIN - 1) {
                    fputs ("error: replaced length would exeed size.\n",
                            stderr);
                    return;
                }
                if (!p[lenword]) {          /* if no following char */
                    memcpy (p, repl, lenrepl);  /* just copy replace */
                    p[lenrepl] = 0;             /* and nul-terminate */
                }
                else {  /* store rest of line in buffer, replace, add end */
                    char endbuf[MAXLIN];    /* temp buffer for end */
                    size_t lenend = strlen (p + lensrch);   /* end length */
                    memcpy (endbuf, p + lensrch, lenend + 1); /* copy end */
                    memcpy (p, repl, lenrepl);  /* make replacement */
                    memcpy (p + lenrepl, endbuf, lenend); /* add end after */
                }
            }
            else {  /* otherwise replace is shorter than search */
                size_t lenend = strlen (p + lenword);   /* get end length */
                memcpy (p, repl, lenrepl);              /* copy replace */
                /* move end to after replace */
                memmove (p + lenrepl, p + lenword, lenend + 1);
            }
        }
    }
}

int main (int argc, char **argv) {

    char str[MAXLIN] = "apple tree house in the elm tree";
    const char  *search = argc > 1 ? argv[1] : "tree",
                *replace = argc > 2 ? argv[2] : "12",
                *delim = " \t\n";

    wordreplace (str, search, replace, delim);

    printf ("str: %s\n", str);
}

使用/输出示例

您在"apple tree house in the elm tree" 中将"tree" 替换为"12" 示例:

$ ./bin/wordrepl_strstr_strcspn
str: apple 12 house in the elm 12

"tree" 与 "core" 的简单等长替换,例如

$ ./bin/wordrepl_strstr_strcspn tree core
str: apple core house in the elm core

"tree" 的“长于”替换为 "bobbing":

$ ./bin/wordrepl_strstr_strcspn tree bobbing
str: apple bobbing house in the elm bobbing

有很多不同的方法可以解决这个问题,所以没有一种方法是正确的。关键是使其易于理解和合理有效。如果您还有其他问题,请仔细查看并告诉我。

【讨论】:

    猜你喜欢
    • 2018-03-17
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    • 2019-02-13
    • 2018-06-21
    • 2014-11-02
    • 2020-05-30
    相关资源
    最近更新 更多