For string, find and replace

前端 未结 6 963
盖世英雄少女心
盖世英雄少女心 2020-12-16 08:03

Finding some text and replacing it with new text within a C string can be a little trickier than expected. I am searching for an algorithm which is fast, and that has a smal

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-16 08:22

    here is a nice code

    #include 
    #include 
    
    char *replace_str(char *str, char *orig, char *rep)
    {
      static char buffer[4096];
      char *p;
    
      if(!(p = strstr(str, orig)))  // Is 'orig' even in 'str'?
        return str;
    
      strncpy(buffer, str, p-str); // Copy characters from 'str' start to 'orig' st$
      buffer[p-str] = '\0';
    
      sprintf(buffer+(p-str), "%s%s", rep, p+strlen(orig));
    
      return buffer;
    }
    
    int main(void)
    {
      puts(replace_str("Hello, world!", "world", "Miami"));
    
      return 0;
    }
    

提交回复
热议问题