简体   繁体   English

子串替换

[英]Substring replace

I want to implement ac code such that it replaces only the exact matching not part of another string.我想实现 ac 代码,以便它只替换完全匹配而不是另一个字符串的一部分。 check out my code.看看我的代码。

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

the above code gives the output : This is sampled simple string上面的代码给出了输出:这是采样的简单字符串

I want the output to be : This is simpled sample string我希望输出是:这是简单的示例字符串

please help请帮忙

Thanks.谢谢。

The best way to deal with these types of question is consider each and every word one-by-one .对付这类问题的最好方法是考虑每一个一个接一个 And then check whether, the pattern (which we are looking for?) is present in the given string or not, if yes then replace it with replacing word .然后检查pattern (我们正在寻找pattern ?)是否存在于给定的字符串中,如果是,则将其替换为替换word

Below is my code.下面是我的代码。 (I know it may seem bit odd one out, but trust me it will work for any pattern-matching and replacement problem) . (我知道它可能看起来有点奇怪,但相信我它可以解决任何模式匹配和替换问题) It will reduce and expand the final output according to the given pattern word and its corresponding replacement 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;
}

If i'm still missing any test case.如果我仍然缺少任何测试用例。 I will be pleased to know about it.我会很高兴知道这件事。

A word can start with space or may lie at the start of string and can end with a space, a full stop, a comma or with the end of string.一个单词可以以空格开头,也可以位于字符串的开头,并且可以以空格、句号、逗号或字符串结尾结尾。 using these conditions you can easily identify any word within a string.使用这些条件,您可以轻松识别字符串中的任何单词。 Following code describes it according to your example.以下代码根据您的示例对其进行了描述。

Using this code you can replace a word with another word of any size.使用此代码,您可以用任意大小的另一个单词替换一个单词。

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

First, you need search the entire string continuously until no substring is found, second, you need check the char before and after the substring returned by strstr, to make sure that the found substring is a complete word.首先需要连续搜索整个字符串,直到没有找到子字符串;其次,需要检查strstr返回的子字符串前后的char,以确保找到的子字符串是一个完整的单词。 When check for word boundary, take special care when the word is at the beginning or end of the longer string.检查单词边界时,请特别注意单词位于较长字符串的开头或结尾。 For example:例如:

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

I updated my code.This deals with the replacement that you want.我更新了我的代码。这涉及您想要的替换。

#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