search

Home  >  Q&A  >  body text

C++ 如何替换Char*类型变量里的字符串?

一个Char *类型的变量
如何替换它里面的某个字符串(如:Like)为空,或者删除该字符串?
遍历替换字符我知道该怎么做,但字符串呢?(不能遍历一个个的字符去替换,因为这个Char里也有可能包含了多个L,但我只需要替换Like里的L就行了)

伊谢尔伦伊谢尔伦2767 days ago619

reply all(3)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 15:17:39

    First find out the positions of all pattern strings. After writing them down, you can strcpy them into a new string in sections.

    reply
    0
  • PHPz

    PHPz2017-04-17 15:17:39

    Resolved:

    char* del_char(char str[])
    {
        int i = 0, j = 0;
        int ii=strlen(str)-strlen(strstr(str,"要删除的子串"));
        while(str[i] != 'rrreee')
        {
            if((ii <= i)&&(ii+X >= i)) //X代表要删除子串的长度-1
            {
                i++;
            }
            else
            {
                str[j++] = str[i++];
            }
        }
        str[j] = 'rrreee';
        return str;
    }

    Loop traversal, the efficiency is a bit low...

    reply
    0
  • PHPz

    PHPz2017-04-17 15:17:39

    If your compiler supports C++11 regex, this replacement is easy to achieve using regular expressions and strings.

    reply
    0
  • Cancelreply