How to find and replace string?

后端 未结 10 1133
感动是毒
感动是毒 2020-11-27 03:51

If s is a std::string, then is there a function like the following?

s.replace(\"text to replace\", \"new text\");
10条回答
  •  我在风中等你
    2020-11-27 03:58

    void replace(char *str, char *strFnd, char *strRep)
    {
        for (int i = 0; i < strlen(str); i++)
        {
            int npos = -1, j, k;
            if (str[i] == strFnd[0])
            {
                for (j = 1, k = i+1; j < strlen(strFnd); j++)
                    if (str[k++] != strFnd[j])
                        break;
                npos = i;
            }
            if (npos != -1)
                for (j = 0, k = npos; j < strlen(strRep); j++)
                    str[k++] = strRep[j];
        }
    
    }
    
    int main()
    {
        char pst1[] = "There is a wrong message";
        char pfnd[] = "wrong";
        char prep[] = "right";
    
        cout << "\nintial:" << pst1;
    
        replace(pst1, pfnd, prep);
    
        cout << "\nfinal : " << pst1;
        return 0;
    }
    

提交回复
热议问题