Replace char in string with some string inplace

前端 未结 4 1697
刺人心
刺人心 2021-01-14 16:16


i want to replace a character in the string with a string. can i do it in-place? As the new string has length greater than original string.Question is that can i do with

4条回答
  •  执笔经年
    2021-01-14 16:54

    i tried this old-fashioned stuff and i think it works. here it is. i am not sure that this would work on encodings other than ascii.

    #include 
    #include 
    
    std::string
    replace_char_with_string
        (const char *in_p,
         char  from_ch,
         const char *to_p)
    {
        char output_c_str[strlen(in_p)*2+1], *out_p = output_c_str;
        int  to_len = strlen(to_p);
    
        while (*in_p)
        {
            if (*in_p == from_ch)
            {
                strcpy(out_p, to_p);
                out_p += to_len;
            }
            else
            {
                *out_p++ = *in_p;
            }
    
            ++in_p;
        }
        *out_p = '\0';
    
        std::string output(output_c_str);
        return output;
    }
    
    // example usage
    std::string java_namespace_name = "com.foo.boo";
    std::string cpp_namespace_name = replace_char_with_string(java_namespace_name.c_str()
    

提交回复
热议问题