单词替换字符串c

时间:2015-12-13 16:00:04

标签: c string function malloc

如何更改此代码以替换字符串中单词的每个外观,但不会替换所有子字符串。例如,如果单词 ask 将不会替换任务询问。因此,对于输入:“我要求问一个任务问我的朋友”和替换词:“for”输出应该是:“我正在为我的朋友请求任务”。

char *replace_word(char *string, char *word, char *new_word) {
    int len = strlen(string) + 1;
    char *temp = malloc(len * sizeof(char));
    int temp_len = 0;
    char *found;
    int len_w = strlen(word);
    while (found = strstr(string, word)) {
            if ((isalnum(*(found - 1))) || (isalnum(*(found + len_w)))) {
                    break;
            }
            else {

                    memcpy(temp + temp_len, string, found - string);

                    temp_len = temp_len + found - string;

                    string = found + strlen(word);

                    len = len - strlen(word) + strlen(new_word);
                    temp = realloc(temp, len * sizeof(char));

                    memcpy(temp + temp_len, new_word, strlen(new_word));

                    temp_len = temp_len + strlen(new_word);
            }
   }

    strcpy(temp + temp_len, string);

return temp;
  }

在这个阶段,输入是:“它问我这个任务吗?”。输出是:“这对我来说是这个任务吗?”但如果输入是这样的:“我问这个问朋友”,输出将与输入相同,因此代码不会进行更改。需要帮忙!

2 个答案:

答案 0 :(得分:0)

好的,所以会发生的事情是,在发现子字符串中出现单词时,while循环会中断;

if ((isalnum(*(found - 1))) || (isalnum(*(found + len_w)))) {
                break;
        }

相反,它应该复制单词和之前的所有内容,以便while不会进入无限循环,因为它一遍又一遍地发现相同的事件。 这种改变应该有效:

char *replace_word(char *string, char *word, char *new_word) {
    int len = strlen(string) + 1;
    char *temp = malloc(len * sizeof(char));
    int temp_len = 0;
    char *found;
    int len_w = strlen(word);
    while (found = strstr(string, word)) {
            if ((isalnum(*(found - 1))) || (isalnum(*(found + len_w)))) {
          memcpy(temp + temp_len, string, found - string + strlen(word));

          temp_len = temp_len + found - string + strlen(word);

          string = found + strlen(word);

            }
            else {

                    memcpy(temp + temp_len, string, found - string);

                    temp_len = temp_len + found - string;

                    string = found + strlen(word);

                    len = len - strlen(word) + strlen(new_word);
                    temp = realloc(temp, len * sizeof(char));

                    memcpy(temp + temp_len, new_word, strlen(new_word));

                    temp_len = temp_len + strlen(new_word);
            }
   }

    strcpy(temp + temp_len, string);

return temp;
  }

答案 1 :(得分:0)

您在代码中还有其他一些问题,但是:

       if ((isalnum(*(found - 1))) || (isalnum(*(found + len_w)))) {
                break;
        }

这是核心问题 - 一旦你确定这个单词被一个字母数字字符包围,你想跳到下一个出现,但你在这里做的是完全打破循环。

您想要做的是:

        if ((isalnum(*(found - 1))) || (isalnum(*(found + len_w)))) {
                continue;
        }

'break'打破循环。

'继续'继续到下一次迭代。

确保在找到每个匹配项后更新字符串,否则您将陷入无休止的循环,从strstr()函数反复获取相同的指针。