【问题标题】:Replace a character in a string with a string in C用 C 中的字符串替换字符串中的字符
【发布时间】:2019-05-09 09:50:58
【问题描述】:

让下面的例子代码:

char s1[] = "Hey there #!";
char s2[] = "Lou";

我想编写一个函数,将 '#' 替换为 s2 的值。它还为具有新替换版本的新输出字符串动态分配内存。 是否有可能以一种优雅且不复杂的方式,主要使用内置函数? 我知道如何用字符串中的字符或给定子字符串的字符串替换字符,但这个似乎打败了我。

【问题讨论】:

    标签: c string replace substring character


    【解决方案1】:

    看看这个 https://stackoverflow.com/a/32496721/5326843 据此,没有替换字符串的标准函数。你必须自己写。

    【讨论】:

    • 是的,我知道,但这不是我想要的输出。我想用另一个字符串而不是另一个字符替换字符串中的一个字符。
    • 你不能修改那个函数吗?
    【解决方案2】:

    你将不得不通过几个函数,但是......这里是:

    #include <string.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        char s1[] = "Hey there #!";
        char s2[] = "Lou";
    
        // Get the resulting length: s1, plus s2,
        // plus terminator, minus one replaced character
        // (the last two cancelling each other out).
        char * s3 = malloc( strlen( s1 ) + strlen( s2 ) );
    
        // The number of characters of s1 that are not "#".
        // This does search for "any character from the second
        // *string*", so "#", not '#'.
        size_t pos = strcspn( s1, "#" );
    
        // Copy up to '#' from s1
        strncpy( s3, s1, pos );
    
        // Append s2
        strcat( s3, s2 );
    
        // Append from s1 after the '#'
        strcat( s3, s1 + pos + 1 );
    
        // Check result.
        puts( s3 );
    }
    

    这并不像你能做到的那样高效(尤其是多次strcat() 调用效率低下),但它以最“简单”的方式仅使用标准函数,并且本身不做任何“指针” .

    【讨论】:

      【解决方案3】:

      没有单个 libc 调用,但可以使用多个 libc 调用,如下所示,不需要动态分配。

          #include <stdio.h>
          #include <string.h>
          char* replace_string(char* str, char* find, char* replace_str)
          {
              int len  = strlen(str);
              int len_find = strlen(find), len_replace = strlen(replace_str);
              for (char* ptr = str; ptr = strstr(ptr, find); ++ptr) {
                  if (len_find != len_replace) 
                      memmove(ptr+len_replace, ptr+len_find,
                          len - (ptr - str) + len_replace);
                  memcpy(ptr, replace_str, len_replace);
              }
              return str;
          }
      
          int main(void)
          {
              char str[] = "Hey there #!";
              char str_replace[] = "Lou";
              printf("%s\n", replace_string(str, "#", str_replace));
              return 0;
          }
      

      输出:

      Hey there Lou!
      

      【讨论】:

        猜你喜欢
        • 2011-10-20
        • 2014-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-09
        • 1970-01-01
        • 2021-04-24
        • 1970-01-01
        相关资源
        最近更新 更多