簡體   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