子串替换

时间:2016-04-16 07:31:44

标签: c string

我想实现一个c代码,它只替换完全匹配而不是另一个字符串的一部分。 看看我的代码。

#include <stdio.h>
#include <string.h>
int main ()
{
   char str[] ="This is a simpled simple string";
   char * pch;
   char str1[]= "simple";
   pch = strstr (str,str1);
   strncpy (pch,"sample",6);
   puts (str);
   return 0;
 }

上面的代码给出了输出:这是采样简单字符串

我希望输出为:这是简单的示例字符串

请帮助

感谢。

4 个答案:

答案 0 :(得分:1)

处理这些类型问题的最佳方法是逐步考虑每个 。然后检查pattern (我们正在寻找?)是否存在于给定字符串中,如果是,则将其替换为替换word

以下是我的代码。 (我知道这看起来有点奇怪,但相信我它会适用于任何模式匹配和替换问题)。根据给定的pattern字及其对应的replacement字,减少展开最终输出。

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

int main() {
    /*    This program will replace the "demo" with "program"    */
    char input[] = "   isdemo Hello this is demo. replace demo with demoes something else demo";
    char pattern[] = "demo";
    char replace[] = "program";
    char output[105];
    int index = 0;

    /*Read the the input line word-by-word, 
      if the word == pattern[], then replace it else do nothing */
      for(int i=0; i<strlen(input);) {
          while(i<strlen(input) && !isalpha(input[i])) {
              output[index++] = input[i++];
          }

          char temp[105]; int j = 0;
          while(i<strlen(input) && isalpha(input[i])) {
              temp[j++] = input[i++];
          } 
          temp[j] = 0;

          if(strcmp(temp, pattern) == 0) {
             strncpy(output+index, replace, strlen(replace));
             index += strlen(replace);
          } else {
             strncpy(output+index, temp, strlen(temp));
             index += strlen(temp);
          }
      }

      output[index] = 0;
      puts(output);

    return 0;
}

如果我仍然遗漏任何测试用例。我很高兴知道这件事。

答案 1 :(得分:0)

单词可以以空格开头,也可以位于字符串的开头,可以以空格,句号,逗号或字符串结尾结束。使用这些条件,您可以轻松识别字符串中的任何单词。以下代码根据您的示例对其进行描述。

使用此代码,您可以将其替换为任意大小的其他字词。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
    char str[] = "simple This is a simpled simple simple. simple, string simple";
    char * pch;
    char * result = str;
    char * temp;

    char str1[] = "simple"; //string to be replaced
    char str2[] = "sample"; //string to be replaced with

    pch = strstr(result, str1);
    while(pch)
    {
        temp = result;
        if ((pch == str || *(pch - 1) == ' ') && (strlen(pch) == strlen(str1) || !isalpha(*(pch + strlen(str1)))))
        {
            result = (char*)malloc(strlen(temp)+(strlen(str2) - strlen(str1))+1); //allocate new memory, +1 for trailing null character
            strncpy(result, temp, pch - temp); // copy previous string till found word to new allocated memory
            strncpy(result + (pch - temp), str2, strlen(str2)); // replace previous word with new word
            strncpy(result + (pch - temp) + strlen(str2), pch + strlen(str1), strlen(pch + strlen(str1))); // place previous string after replaced word
            strncpy(result + strlen(temp) + (strlen(str2) - strlen(str1)), "\0", 1); // place null character at the end of string
            if (temp != str)
                free(temp); // free extra memory
        }
        pch = strstr(result + (pch - temp) + 1, str1); // search for another word in new string after the last word was replaced
    }

    puts(result);
    if (result != str)
        free(result);
    return 0;
}

答案 2 :(得分:0)

首先,您需要连续搜索整个字符串,直到找不到子字符串,其次,您需要检查strstr返回的子字符串之前和之后的字符,以确保找到的子字符串是一个完整的字。检查单词边界时,请在单词位于较长字符串的开头或结尾时特别小心。例如:

#include <stdio.h>
#include <string.h>
int main(void)
{
    char str[] ="simple simples is a simpled simple string simple";
    char *s = str;
    char *pch = str;
    char str1[]= "simple";
    int len = strlen(str1);
    int pos;
    while (1) {
        pch = strstr(s, str1);
        if (!pch)  // no more occurrences of str1, quit
            break;
        pos = pch - str;
        if (pos == 0) { // if it's the beginning
            if (!isalpha(pch[len])) {
                strncpy(pch, "sample", 6);
            }
        } else { // check two ends
            if (!isalpha(*(pch-1)) && !isalpha(*(pch+len))) {
                    strncpy(pch, "sample", 6);
            }
        }
        s = pch + len;
   }
   puts(str);
   return 0;
}

答案 3 :(得分:0)

我更新了我的代码。这涉及您想要的替换。

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

void replace(char *buf, size_t bufSize, const char *word_to_replace, const char *replacement_word);

int main(void)
{
    char str[100] = "simple Asimple simpleB This is a simpled simple string and simple is good sometimes!, simple";
    replace(str, sizeof(str), "simple", "sample");
    printf("%s\n", str);
    return 0;
}

void replace(char *buf, size_t bufSize, const char *word_to_replace, const char *replacement_word)
{
    size_t buf_len = strlen(buf), word_len = strlen(word_to_replace);
    char *ptr = strstr(buf, word_to_replace);
    if (ptr == NULL) {
        fprintf(stderr, "Could not find matches.\n");
        return;
    }
    bool _G = 0;
    char *tmp = (char *)malloc(bufSize);

    // Deal with begining of line
    if (ptr == buf) {
        if (ptr[word_len] == ' ' || ptr[word_len] == '\0') {
            _G = 1;
        }
        if (_G) {
            strcpy_s(tmp, bufSize, ptr + word_len);
            *ptr = 0;
            strcat_s(buf, bufSize, replacement_word);
            strcat_s(buf, bufSize, tmp);
            _G = 0;
        }
    }
    else {
        if (*(ptr - 1) == ' ' && (ptr[word_len] == ' ' || ptr[word_len] == '\0')) {
            _G = 1;
        }
        if (_G) {
            strcpy_s(tmp, bufSize, ptr + word_len);
            *ptr = 0;
            strcat_s(buf, bufSize, replacement_word);
            strcat_s(buf, bufSize, tmp);
            _G = 0;
        }
    }
    // deal with the rest
    while (ptr = strstr(ptr + 1, word_to_replace))
    {
        if (*(ptr - 1) == ' ' && (ptr[word_len] == ' ' || ptr[word_len] == '\0')) {
            _G = 1;
        }
        if (_G) {
            strcpy_s(tmp, bufSize, ptr + word_len);
            *ptr = 0;
            strcat_s(buf, bufSize, replacement_word);
            strcat_s(buf, bufSize, tmp);
            _G = 0;
        }
    }
    free(tmp);
}