C++ 如何查找和替换字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5878775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find and replace string?
提问by neuromancer
If s
is a std::string
, then is there a function like the following?
如果s
是 a std::string
,那么是否有如下函数?
s.replace("text to replace", "new text");
回答by Mateen Ulhaq
Try a combination of std::string::find
and std::string::replace
.
尝试组合std::string::find
和std::string::replace
。
This gets the position:
这得到了位置:
std::string s;
std::string toReplace("text to replace");
size_t pos = s.find(toReplace);
And this replaces the firstoccurrence:
这取代了第一次出现:
s.replace(pos, toReplace.length(), "new text");
Now you can simply create a function for your convenience:
现在您可以简单地创建一个函数来方便您:
std::string replaceFirstOccurrence(
std::string& s,
const std::string& toReplace,
const std::string& replaceWith)
{
std::size_t pos = s.find(toReplace);
if (pos == std::string::npos) return s;
return s.replace(pos, toReplace.length(), replaceWith);
}
回答by Czarek Tomczak
Do we really need a Boost library for seemingly such a simple task?
我们真的需要一个 Boost 库来完成看似如此简单的任务吗?
To replace all occurences of a substring use this function:
要替换所有出现的子字符串,请使用此函数:
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;
}
If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:
如果您需要性能,这里是一个修改输入字符串的优化函数,它不会创建字符串的副本:
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();
}
}
Tests:
测试:
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;
Output:
输出:
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
回答by phooji
Yes: replace_all
is one of the boost string algorithms:
是:replace_all
是增强字符串算法之一:
Although it's not a standard library, it has a few things on the standard library:
虽然它不是标准库,但它在标准库上有一些东西:
- More natural notationbased on ranges rather than iterator pairs. This is nice because you can nest string manipulations (e.g.,
replace_all
nested inside atrim
). That's a bit more involved for the standard library functions. - Completeness.This isn't hard to be 'better' at; the standard library is fairly spartan. For example, the boost string algorithms give you explicit control over how string manipulations are performed (i.e., in place or through a copy).
- 基于范围而不是迭代器对的更自然的表示法。这很好,因为您可以嵌套字符串操作(例如,
replace_all
嵌套在 a 中trim
)。这对于标准库函数来说涉及更多。 - 完整性。这并不难“更好”;标准库相当简陋。例如,boost 字符串算法使您可以明确控制如何执行字符串操作(即,就地或通过副本)。
回答by Mark Tolonen
#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;
}
Output
输出
one five two four
回答by Sylvain Rochette
like some say boost::replace_all
就像有人说 boost::replace_all
here a dummy example:
这是一个虚拟示例:
#include <boost/algorithm/string/replace.hpp>
std::string path("file.gz");
boost::replace_all(path, ".gz", ".zip");
回答by Nawaz
Not exactly that, but std::string
has many replace
overloaded functions.
不完全是这样,但std::string
有许多replace
重载的功能。
Go through this linkto see explanation of each, with examples as to how they're used.
Also, there are several versions of string::find
functions (listed below) which you can use in conjunction with string::replace
.
此外,还有多个版本的string::find
函数(如下所列)可以与string::replace
.
- find
- rfind
- find_first_of
- find_last_of
- find_first_not_of
- find_last_not_of
- 找
- 找到
- find_first_of
- find_last_of
- find_first_not_of
- find_last_not_of
Also, note that there are several versions of replace
functions available from <algorithm>
which you can also use (instead of string::replace
):
另外,请注意,您还可以使用多个版本的replace
函数<algorithm>
(而不是string::replace
):
- replace
- replace_if
- replace_copy
- replace_copy_if
- 代替
- 替换_如果
- 替换_复制
- replace_copy_if
回答by Bayram AKGüL
// 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];
}
}
}
回答by anisoptera
Here's the version I ended up writing that replaces all instances of the target string in a given string. Works on any string type.
这是我最终编写的版本,它替换了给定字符串中目标字符串的所有实例。适用于任何字符串类型。
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;
}
Example:
例子:
auto foo = "this is a test"s;
replace(foo, "is"s, "wis"s);
cout << foo;
Output:
输出:
thwis wis a test
Note that even if the search string appears in the replacement string, this works correctly.
请注意,即使搜索字符串出现在替换字符串中,这也能正常工作。
回答by snb
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;
}
回答by Shubham Agrawal
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());
}
}
More CPP utilities: https://github.com/Heyshubham/CPP-Utitlities/blob/master/src/MEString.cpp#L60
更多 CPP 实用程序:https: //github.com/Heyshubham/CPP-Utilities/blob/master/src/MEString.cpp#L60