c++中wstring字符串替换怎么实现

2024-04-24

在C++中,可以使用下面的方法来实现wstring字符串的替换:

#include <iostream>
#include <string>

int main() {
    std::wstring str = L"Hello, world!";
    std::wstring oldStr = L"world";
    std::wstring newStr = L"C++";
    
    size_t pos = 0;
    while ((pos = str.find(oldStr, pos)) != std::wstring::npos) {
        str.replace(pos, oldStr.length(), newStr);
        pos += newStr.length();
    }
    
    std::wcout << str << std::endl;
    
    return 0;
}

在上面的代码中,我们首先定义了一个wstring类型的字符串str,然后定义了要替换的旧字符串oldStr和新字符串newStr。接着使用find函数找到旧字符串在str中的位置,然后使用replace函数将旧字符串替换为新字符串。最后输出替换后的字符串。