繁体   English   中英

子串替换

[英]Substring replace

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

#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;
 }

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

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

请帮忙

谢谢。

对付这类问题的最好方法是考虑每一个一个接一个 然后检查pattern (我们正在寻找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;
}

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

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

使用此代码,您可以用任意大小的另一个单词替换一个单词。

#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;
}

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

#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;
}

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

#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);
}

暂无
暂无

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

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