Answers:
std::string
不包含此类功能,但您可以使用标头中的独立replace
功能algorithm
。
#include <algorithm>
#include <string>
void some_func() {
std::string s = "example string";
std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}
std::string::replace()
代替的std::replace()
!'x'(char
)被隐式强制转换为size_t
[值120],因此整个字符串或字符串的一部分(或部分)将被120个'y'副本填充。
我还以为我会加入boost解决方案:
#include <boost/algorithm/string/replace.hpp>
// in place
std::string in_place = "blah#blah";
boost::replace_all(in_place, "#", "@");
// copy
const std::string input = "blah#blah";
std::string output = boost::replace_all_copy(input, "#", "@");
-I
用于编译器的标志,以便编译器在系统上找到Boost库。也许您甚至需要先安装它。
问题集中在character
替换上,但是,正如我发现此页面非常有用(尤其是Konrad的评论),我想分享这个更通用的实现,它也可以处理substrings
:
std::string ReplaceAll(std::string str, const std::string& from, const std::string& to) {
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
}
return str;
}
用法:
std::cout << ReplaceAll(string("Number Of Beans"), std::string(" "), std::string("_")) << std::endl;
std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("X")) << std::endl;
std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("h")) << std::endl;
输出:
豆数
XXjXugtXty
hhjhugthty
编辑:
如果您需要关注性能,可以通过不返回任何值(void
)并直接对str
作为参数给出的字符串进行更改(通过地址而不是通过value)来执行上述操作。这样可以避免在返回结果的同时浪费无用和昂贵的原始字符串副本。那你的电话
代码:
static inline void ReplaceAll2(std::string &str, const std::string& from, const std::string& to)
{
// Same inner code...
// No return statement
}
希望这对其他人有帮助...
from
string是否为空,否则会发生无限循环。
设想一个大的二进制Blob,其中所有0x00字节都应由“ \ 1 \ x30”替换,而所有0x01字节均应由“ \ 1 \ x31”替换,因为传输协议不允许\ 0字节。
在下列情况下:
提供的解决方案无法应用(因为它们仅替换单个字符)或存在性能问题,因为它们将多次调用string :: replace,从而一遍又一遍地生成blob大小的副本。(我不知道增强解决方案,也许从这个角度来看还可以)
这一个沿源字符串中所有出现的散步和建立一块新的字符串件一次:
void replaceAll(std::string& source, const std::string& from, const std::string& to)
{
std::string newString;
newString.reserve(source.length()); // avoids a few memory allocations
std::string::size_type lastPos = 0;
std::string::size_type findPos;
while(std::string::npos != (findPos = source.find(from, lastPos)))
{
newString.append(source, lastPos, findPos - lastPos);
newString += to;
lastPos = findPos + from.length();
}
// Care for the rest after last occurrence
newString += source.substr(lastPos);
source.swap(newString);
}
一个简单的查找和替换单个字符将类似于:
s.replace(s.find("x"), 1, "y")
要对整个字符串执行此操作,最简单的方法是循环播放,直到您s.find
开始返回为止npos
。我想您也range_error
可以退出循环,但这有点丑陋。
{
角色是“支撑” 。我不知道什么是“双括号”。也许您有某种字体问题?
如果您要替换多个字符并且仅处理std::string
,则此代码段将起作用,用sReplace替换sHaystack中的sNeedle,并且sNeedle和sReplace不必大小相同。该例程使用while循环替换所有出现的内容,而不仅仅是从左到右找到的第一个。
while(sHaystack.find(sNeedle) != std::string::npos) {
sHaystack.replace(sHaystack.find(sNeedle),sNeedle.size(),sReplace);
}
find
两次通话。考虑使该结果成为临时变量。
#include <iostream>
#include <string>
using namespace std;
// Replace function..
string replace(string word, string target, string replacement){
int len, loop=0;
string nword="", let;
len=word.length();
len--;
while(loop<=len){
let=word.substr(loop, 1);
if(let==target){
nword=nword+replacement;
}else{
nword=nword+let;
}
loop++;
}
return nword;
}
//Main..
int main() {
string word;
cout<<"Enter Word: ";
cin>>word;
cout<<replace(word, "x", "y")<<endl;
return 0;
}
word
很长,则在调用函数时可能会有很多开销。你可以通过这个优化word
,target
以及replacement
为const引用。
那Abseil StrReplaceAll呢?从头文件:
// This file defines `absl::StrReplaceAll()`, a general-purpose string
// replacement function designed for large, arbitrary text substitutions,
// especially on strings which you are receiving from some other system for
// further processing (e.g. processing regular expressions, escaping HTML
// entities, etc.). `StrReplaceAll` is designed to be efficient even when only
// one substitution is being performed, or when substitution is rare.
//
// If the string being modified is known at compile-time, and the substitutions
// vary, `absl::Substitute()` may be a better choice.
//
// Example:
//
// std::string html_escaped = absl::StrReplaceAll(user_input, {
// {"&", "&"},
// {"<", "<"},
// {">", ">"},
// {"\"", """},
// {"'", "'"}});
老套 :-)
std::string str = "H:/recursos/audio/youtube/libre/falta/";
for (int i = 0; i < str.size(); i++) {
if (str[i] == '/') {
str[i] = '\\';
}
}
std::cout << str;
结果:
H:\ recursos \ audio \ youtube \ libre \ falta \
这可行!对于书店应用程序,我使用了类似的方法,其中库存存储在CSV中(如.dat文件)。但是对于单个字符,意味着替换者只是单个字符,例如'|',它必须用双引号“ |”表示。为了不抛出无效的转换const char。
#include <iostream>
#include <string>
using namespace std;
int main()
{
int count = 0; // for the number of occurences.
// final hold variable of corrected word up to the npos=j
string holdWord = "";
// a temp var in order to replace 0 to new npos
string holdTemp = "";
// a csv for a an entry in a book store
string holdLetter = "Big Java 7th Ed,Horstman,978-1118431115,99.85";
// j = npos
for (int j = 0; j < holdLetter.length(); j++) {
if (holdLetter[j] == ',') {
if ( count == 0 )
{
holdWord = holdLetter.replace(j, 1, " | ");
}
else {
string holdTemp1 = holdLetter.replace(j, 1, " | ");
// since replacement is three positions in length,
// must replace new replacement's 0 to npos-3, with
// the 0 to npos - 3 of the old replacement
holdTemp = holdTemp1.replace(0, j-3, holdWord, 0, j-3);
holdWord = "";
holdWord = holdTemp;
}
holdTemp = "";
count++;
}
}
cout << holdWord << endl;
return 0;
}
// result:
Big Java 7th Ed | Horstman | 978-1118431115 | 99.85
我通常不习惯使用CentOS,因此下面是我的编译器版本。C ++版本(g ++),C ++ 98默认值:
g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
如果愿意使用std::string
s,则可以strsub
按原样使用此示例应用程序的功能,如果希望采用不同类型或一组参数来实现大致相同的目标,则可以对其进行更新。基本上,它使用的特性和功能std::string
来快速擦除匹配的字符集,并将所需的字符直接插入std::string
。每次执行此替换操作时,偏移量都会更新,如果它仍然可以找到匹配的字符进行替换,并且由于无法替换而无法替换,则它将返回上一次更新后的状态的字符串。
#include <iostream>
#include <string>
std::string strsub(std::string stringToModify,
std::string charsToReplace,
std::string replacementChars);
int main()
{
std::string silly_typos = "annoiiyyyng syyyllii tiipos.";
std::cout << "Look at these " << silly_typos << std::endl;
silly_typos = strsub(silly_typos, "yyy", "i");
std::cout << "After a little elbow-grease, a few less " << silly_typos << std::endl;
silly_typos = strsub(silly_typos, "ii", "y");
std::cout << "There, no more " << silly_typos << std::endl;
return 0;
}
std::string strsub(std::string stringToModify,
std::string charsToReplace,
std::string replacementChars)
{
std::string this_string = stringToModify;
std::size_t this_occurrence = this_string.find(charsToReplace);
while (this_occurrence != std::string::npos)
{
this_string.erase(this_occurrence, charsToReplace.size());
this_string.insert(this_occurrence, replacementChars);
this_occurrence = this_string.find(charsToReplace,
this_occurrence + replacementChars.size());
}
return this_string;
}
如果您不希望使用std::string
s作为参数,而是可以传递C样式的字符串,则可以在下面看到更新的示例:
#include <iostream>
#include <string>
std::string strsub(const char * stringToModify,
const char * charsToReplace,
const char * replacementChars,
uint64_t sizeOfCharsToReplace,
uint64_t sizeOfReplacementChars);
int main()
{
std::string silly_typos = "annoiiyyyng syyyllii tiipos.";
std::cout << "Look at these " << silly_typos << std::endl;
silly_typos = strsub(silly_typos.c_str(), "yyy", "i", 3, 1);
std::cout << "After a little elbow-grease, a few less " << silly_typos << std::endl;
silly_typos = strsub(silly_typos.c_str(), "ii", "y", 2, 1);
std::cout << "There, no more " << silly_typos << std::endl;
return 0;
}
std::string strsub(const char * stringToModify,
const char * charsToReplace,
const char * replacementChars,
uint64_t sizeOfCharsToReplace,
uint64_t sizeOfReplacementChars)
{
std::string this_string = stringToModify;
std::size_t this_occurrence = this_string.find(charsToReplace);
while (this_occurrence != std::string::npos)
{
this_string.erase(this_occurrence, sizeOfCharsToReplace);
this_string.insert(this_occurrence, replacementChars);
this_occurrence = this_string.find(charsToReplace,
this_occurrence + sizeOfReplacementChars);
}
return this_string;
}
对于简单的情况,此方法非常有效,无需使用任何其他库,然后再使用std :: string(已在使用)。
替换字符的所有出现一个与人物b在some_string:
for (size_t i = 0; i < some_string.size(); ++i) {
if (some_string[i] == 'a') {
some_string.replace(i, 1, "b");
}
}
如果字符串很大或有多个替换调用是问题,则可以应用此答案中提到的技术:https : //stackoverflow.com/a/29752943/3622300
这是我以最大的DRI精神推出的解决方案。它将在sHaystack中搜索sNeedle,并将其替换为sReplace,如果非零则为nTimes,否则所有sNeedle都将出现。它不会在替换的文本中再次搜索。
std::string str_replace(
std::string sHaystack, std::string sNeedle, std::string sReplace,
size_t nTimes=0)
{
size_t found = 0, pos = 0, c = 0;
size_t len = sNeedle.size();
size_t replen = sReplace.size();
std::string input(sHaystack);
do {
found = input.find(sNeedle, pos);
if (found == std::string::npos) {
break;
}
input.replace(found, len, sReplace);
pos = found + replen;
++c;
} while(!nTimes || c < nTimes);
return input;
}
std::string
是专门设计用于处理字符序列的容器。链接