gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 14:00:21 29 4
gpt4 key购买 nike

如果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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com