【发布时间】:2011-05-04 04:58:12
【问题描述】:
如果s 是std::string,那么是否有类似下面的函数?
s.replace("text to replace", "new text");
【问题讨论】:
-
没有这样的直接替换,但它应该在那里。我也找了很久。
如果s 是std::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");
使用std::ostringstream 作为缓冲区定义这个 O(n) 方法:
void replace_all(
std::string& s,
std::string const& toReplace,
std::string const& replaceWith
) {
std::ostringstream oss;
std::size_t pos = 0;
std::size_t prevPos = pos;
while (true) {
prevPos = pos;
pos = s.find(toReplace, pos);
if (pos == std::string::npos)
break;
oss << s.substr(prevPos, pos - prevPos);
oss << replaceWith;
pos += toReplace.size();
}
oss << s.substr(prevPos);
s = oss.str();
}
用法:
replace_all(s, "text to replace", "new text");
或者,使用boost::algorithm::replace_all:
#include <boost/algorithm/string.hpp>
using boost::replace_all;
用法:
replace_all(s, "text to replace", "new text");
【讨论】:
string 分配内存,填写数据,并删除“旧”string。
toReplace的第一个实例。
对于看似如此简单的任务,我们真的需要 Boost 库吗?
要替换所有出现的子字符串,请使用此函数:
std::string ReplaceString(std::string subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
如果你需要性能,这里有一个优化的函数,它修改输入字符串,它不会创建字符串的副本:
void ReplaceStringInPlace(std::string& subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
测试:
std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;
std::cout << "ReplaceString() return value: "
<< ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not modified: "
<< input << std::endl;
ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: "
<< input << std::endl;
输出:
Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def
【讨论】:
是的:replace_all 是提升字符串算法之一:
虽然不是标准库,但在标准库上却有几样东西:
replace_all 嵌套在 trim 中)。标准库函数涉及的更多。【讨论】:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str("one three two four");
string str2("three");
str.replace(str.find(str2),str2.length(),"five");
cout << str << endl;
return 0;
}
one five two four
【讨论】:
就像有人说 boost::replace_all
这里是一个虚拟的例子:
#include <boost/algorithm/string/replace.hpp>
std::string path("file.gz");
boost::replace_all(path, ".gz", ".zip");
【讨论】:
不完全是这样,但std::string 有许多replace 重载函数。
通过this link查看每个解释,以及如何使用它们的示例。
此外,还有多个版本的string::find 函数(如下所列),您可以将它们与string::replace 结合使用。
另外,请注意<algorithm> 提供了多个版本的replace 函数,您也可以使用它们(而不是string::replace):
【讨论】:
// replaced text will be in buffer.
void Replace(char* buffer, const char* source, const char* oldStr, const char* newStr)
{
if(buffer==NULL || source == NULL || oldStr == NULL || newStr == NULL) return;
int slen = strlen(source);
int olen = strlen(oldStr);
int nlen = strlen(newStr);
if(olen>slen) return;
int ix=0;
for(int i=0;i<slen;i++)
{
if(oldStr[0] == source[i])
{
bool found = true;
for(int j=1;j<olen;j++)
{
if(source[i+j]!=oldStr[j])
{
found = false;
break;
}
}
if(found)
{
for(int j=0;j<nlen;j++)
buffer[ix++] = newStr[j];
i+=(olen-1);
}
else
{
buffer[ix++] = source[i];
}
}
else
{
buffer[ix++] = source[i];
}
}
}
【讨论】:
这是我最终编写的版本,它替换了给定字符串中目标字符串的所有实例。适用于任何字符串类型。
template <typename T, typename U>
T &replace (
T &str,
const U &from,
const U &to)
{
size_t pos;
size_t offset = 0;
const size_t increment = to.size();
while ((pos = str.find(from, offset)) != T::npos)
{
str.replace(pos, from.size(), to);
offset = pos + increment;
}
return str;
}
例子:
auto foo = "this is a test"s;
replace(foo, "is"s, "wis"s);
cout << foo;
输出:
thwis wis a test
请注意,即使搜索字符串出现在替换字符串中,也可以正常工作。
【讨论】:
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;
}
【讨论】:
void replaceAll(std::string & data, const std::string &toSearch, const std::string &replaceStr)
{
// Get the first occurrence
size_t pos = data.find(toSearch);
// Repeat till end is reached
while( pos != std::string::npos)
{
// Replace this occurrence of Sub String
data.replace(pos, toSearch.size(), replaceStr);
// Get the next occurrence from the current position
pos =data.find(toSearch, pos + replaceStr.size());
}
}
更多 CPP 实用程序:https://github.com/Heyshubham/CPP-Utitlities/blob/master/src/MEString.cpp#L60
【讨论】:
有没有类似下面的函数?
另一种(除了使用boost和不同答案中给出的其他方法)可能的方法是使用std::regex_replace,如下所示:
std::string s{"my name is my name and not my name mysometext myto"}; //this is the original line
std::string replaceThis = "my";
std::string replaceWith = "your";
std::regex pattern("\\b" + replaceThis + "\\b");
std::string replacedLine = std::regex_replace(s, pattern, replaceWith);
std::cout<<replacedLine<<std::endl;
【讨论】: