c++ - 如何查找和替换字符串?

标签 c++ string

如果sstd::string,那么有没有类似下面的函数?

s.replace("text to replace", "new text");

最佳答案

替换第一个匹配项

使用 std::string::find 的组合和 std::string::replace .

找到第一个匹配项:

std::string s;
std::string toReplace("text to replace");
size_t pos = s.find(toReplace);

替换第一个匹配项:

s.replace(pos, toReplace.length(), "new text");

为您提供方便的简单功能:

void replace_first(
    std::string& s,
    std::string const& toReplace,
    std::string const& replaceWith
) {
    std::size_t pos = s.find(toReplace);
    if (pos == std::string::npos) return;
    s.replace(pos, toReplace.length(), replaceWith);
}

用法:

replace_first(s, "text to replace", "new text");

Demo.


替换所有匹配项

使用 std::string 定义此 O(n) 方法作为缓冲区:

void replace_all(
    std::string& s,
    std::string const& toReplace,
    std::string const& replaceWith
) {
    std::string buf;
    std::size_t pos = 0;
    std::size_t prevPos;

    // Reserves rough estimate of final size of string.
    buf.reserve(s.size());

    while (true) {
        prevPos = pos;
        pos = s.find(toReplace, pos);
        if (pos == std::string::npos)
            break;
        buf.append(s, prevPos, pos - prevPos);
        buf += replaceWith;
        pos += toReplace.size();
    }

    buf.append(s, prevPos, s.size() - prevPos);
    s.swap(buf);
}

用法:

replace_all(s, "text to replace", "new text");

Demo.


提升

或者,使用 boost::algorithm::replace_all :

#include <boost/algorithm/string.hpp>
using boost::replace_all;

用法:

replace_all(s, "text to replace", "new text");

关于c++ - 如何查找和替换字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5878775/

相关文章:

c++ - 以编程方式创建的 tinyxml xml 文件未在 Internet Explorer 中加载

c++ - 在 C++ 中将字符数组转换为 POD 数组

c++ - get_money() 函数出错

c# - 在字符串中的连续数字后面插入字符串?

arrays - 为什么 C 字符串并不总是等同于字符数组?

javascript - 如何删除字符串的第一个和最后一个字符

c++ - 在 C++ 中将一个数组复制到另一个数组

c++ - *&var 是多余的吗?

string - 从 Go 中的 slice 中删除字符串

C文件比较