如何替换字符串中的所有字符?

时间:2022-09-13 09:31:21

What is the effective way to replace all occurrences of a character with another character in std::string?

如何有效地替换std中另一个字符的所有出现的字符::string?

11 个解决方案

#1


565  

std::string doesn't contain such function but you could use stand-alone replace function from algorithm header.

string不包含这样的函数,但是你可以从算法标题中使用独立的替换函数。

#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'
}

#2


103  

I thought I'd toss in the boost solution as well:

我想我也会在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, "#", "@");

#3


89  

The question is centered on character replacement, but, as I found this page very useful (especially Konrad's remark), I'd like to share this more generalized implementation, which allows to deal with substrings as well:

问题集中在字符替换上,但是,由于我发现这个页面非常有用(特别是Konrad的注释),我想要分享这个更通用的实现,它也允许处理子字符串:

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;
}

Usage:

用法:

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;

Outputs:

输出:

Number_Of_Beans

Number_Of_Beans

XXjXugtXty

XXjXugtXty

hhjhugthty

hhjhugthty


EDIT:

编辑:

The above can be implemented in a more suitable way, in case performances are of your concern, by returning nothing (void) and performing the changes directly on the string str given as argument, passed by address instead of by value. This would avoid useless and costly copy of the original string, while returning the result. Your call, then...

上面的方法可以用更合适的方式实现,例如,通过返回任何东西(void)并直接在string str上执行更改,而不是通过值来传递(void)。这将避免原始字符串的无用且昂贵的副本,同时返回结果。你的电话,然后……

Code :

代码:

static inline void ReplaceAll2(std::string &str, const std::string& from, const std::string& to)
{
    // Same inner code...
    // No return statement
}

Hope this will be helpful for some others...

希望这对其他一些人有帮助…

#4


21  

Imagine a large binary blob where all 0x00 bytes shall be replaced by "\1\x30" and all 0x01 bytes by "\1\x31" because the transport protocol allows no \0-bytes.

想象一个大的二进制blob,所有的0x00字节将被“\1\x30”和所有0x01字节替换为“\1\x31”,因为传输协议不允许\0字节。

In cases where:

在这种情况下,:

  • the replacing and the to-replaced string have different lengths,
  • 替换和替换的字符串有不同的长度,
  • there are many occurences of the to-replaced string within the source string and
  • 在源字符串中有许多被替换的字符串的出现。
  • the source string is large,
  • 源字符串很大,

the provided solutions cannot be applied (because they replace only single characters) or have a performance problem, because they would call string::replace several times which generates copies of the size of the blob over and over. (I do not know the boost solution, maybe it is OK from that perspective)

所提供的解决方案不能应用(因为它们只替换单个字符)或有性能问题,因为它们会调用string::替换多次生成blob大小的副本。(我不知道boost的解决方案,也许从这个角度来看是可以的)

This one walks along all occurrences in the source string and builds the new string piece by piece once:

这一条在源字符串中遍历所有的事件,并一次构建一个新的字符串:

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);
}

#5


17  

A simple find and replace for a single character would go something like:

一个简单的查找和替换一个字符将会是:

s.replace(s.find("x"), 1, "y")

s.replace(s.find(x),1,“y”)

To do this for the whole string, the easy thing to do would be to loop until your s.find starts returning npos. I suppose you could also catch range_error to exit the loop, but that's kinda ugly.

为了整个字符串这样做,很容易做的事情是循环到你的s。发现开始返回非营利组织。我想您也可以捕获range_error来退出循环,但这有点难看。

#6


4  

As Kirill suggested, either use the replace method or iterate along the string replacing each char independently.

如Kirill所建议的,要么使用replace方法,要么在字符串中迭代,独立地替换每个char。

Alternatively you can use the find method or find_first_of depending on what you need to do. None of these solutions will do the job in one go, but with a few extra lines of code you ought to make them work for you. :-)

或者,您可以使用find方法或find_first_of根据需要做什么。这些解决方案都不会一次性完成任务,但是需要额外的几行代码,您应该让它们为您工作。:-)

#7


3  

#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;
}

#8


3  

If you're looking to replace more than a single character, and are dealing only with std::string, then this snippet would work, replacing sNeedle in sHaystack with sReplace, and sNeedle and sReplace do not need to be the same size. This routine uses the while loop to replace all occurrences, rather than just the first one found from left to right.

如果您希望替换多个字符,并且只处理std::string,那么该代码段将工作,用sReplace替换sHaystack中的sNeedle, sNeedle和sReplace不需要相同的大小。这个例程使用while循环来替换所有的事件,而不是从左到右的第一个。

while(sHaystack.find(sNeedle) != std::string::npos) {
  sHaystack.replace(sHaystack.find(sNeedle),sNeedle.size(),sReplace);
}

#9


0  

This works! I used something similar to this for a bookstore app, where the inventory was stored in a CSV (like a .dat file). But in the case of a single char, meaning the replacer is only a single char, e.g.'|', it must be in double quotes "|" in order not to throw an invalid conversion const char.

这个工作!我在一个书店应用程序中使用了类似的东西,其中的库存存储在CSV中(比如.dat文件)。但是在单个char的情况下,意味着替换器仅是一个char,例如'|',它必须是双引号“|”,以便不抛出无效的转换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

Uncustomarily I am using CentOS currently, so my compiler version is below . The C++ version (g++), C++98 default:

通常我现在使用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.

#10


0  

If you're willing to use std::strings, you can use this sample-app's strsub function as-is, or update it if you want it to take a different type or set of parameters to achieve roughly the same goal. Basically, it uses the properties and functionalities of std::string to quickly erase the matching set of characters, and insert the desired characters directly within the std::string. Every time it does this replacement operation, the offset updates if it can still find matching chars to replace, and if it can't due to nothing more to replace, it returns the string in its state from the last update.

如果您愿意使用std::string,您可以使用这个示例应用程序的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;
}

If you don't want to rely on using std::strings as your parameters so you can pass in C-style strings instead, you can see the updated sample below:

如果您不想依赖std::字符串作为参数,那么您可以使用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;
}

#11


0  

For simple situations this works pretty well without using any other library then std::string (which is already in use).

对于简单的情况,这可以很好地运行,而不需要使用任何其他的库,然后std::string(已经在使用中)。

Replace all occurences of character a with character b in some_string:

在some_string中替换字符a与字符b的所有出现:

for (size_t i = 0; i < some_string.size(); ++i) {
    if (some_string[i] == 'a') {
        some_string.replace(i, 1, "b");
    }
}

If the string is large or multiple calls to replace is an issue, you can apply the technique mentioned in this answer: https://*.com/a/29752943/3622300

如果字符串是大的或多个调用来替换是一个问题,那么您可以应用在这个答案中提到的技术:https://*.com/a/29752943/3622300。

#1


565  

std::string doesn't contain such function but you could use stand-alone replace function from algorithm header.

string不包含这样的函数,但是你可以从算法标题中使用独立的替换函数。

#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'
}

#2


103  

I thought I'd toss in the boost solution as well:

我想我也会在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, "#", "@");

#3


89  

The question is centered on character replacement, but, as I found this page very useful (especially Konrad's remark), I'd like to share this more generalized implementation, which allows to deal with substrings as well:

问题集中在字符替换上,但是,由于我发现这个页面非常有用(特别是Konrad的注释),我想要分享这个更通用的实现,它也允许处理子字符串:

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;
}

Usage:

用法:

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;

Outputs:

输出:

Number_Of_Beans

Number_Of_Beans

XXjXugtXty

XXjXugtXty

hhjhugthty

hhjhugthty


EDIT:

编辑:

The above can be implemented in a more suitable way, in case performances are of your concern, by returning nothing (void) and performing the changes directly on the string str given as argument, passed by address instead of by value. This would avoid useless and costly copy of the original string, while returning the result. Your call, then...

上面的方法可以用更合适的方式实现,例如,通过返回任何东西(void)并直接在string str上执行更改,而不是通过值来传递(void)。这将避免原始字符串的无用且昂贵的副本,同时返回结果。你的电话,然后……

Code :

代码:

static inline void ReplaceAll2(std::string &str, const std::string& from, const std::string& to)
{
    // Same inner code...
    // No return statement
}

Hope this will be helpful for some others...

希望这对其他一些人有帮助…

#4


21  

Imagine a large binary blob where all 0x00 bytes shall be replaced by "\1\x30" and all 0x01 bytes by "\1\x31" because the transport protocol allows no \0-bytes.

想象一个大的二进制blob,所有的0x00字节将被“\1\x30”和所有0x01字节替换为“\1\x31”,因为传输协议不允许\0字节。

In cases where:

在这种情况下,:

  • the replacing and the to-replaced string have different lengths,
  • 替换和替换的字符串有不同的长度,
  • there are many occurences of the to-replaced string within the source string and
  • 在源字符串中有许多被替换的字符串的出现。
  • the source string is large,
  • 源字符串很大,

the provided solutions cannot be applied (because they replace only single characters) or have a performance problem, because they would call string::replace several times which generates copies of the size of the blob over and over. (I do not know the boost solution, maybe it is OK from that perspective)

所提供的解决方案不能应用(因为它们只替换单个字符)或有性能问题,因为它们会调用string::替换多次生成blob大小的副本。(我不知道boost的解决方案,也许从这个角度来看是可以的)

This one walks along all occurrences in the source string and builds the new string piece by piece once:

这一条在源字符串中遍历所有的事件,并一次构建一个新的字符串:

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);
}

#5


17  

A simple find and replace for a single character would go something like:

一个简单的查找和替换一个字符将会是:

s.replace(s.find("x"), 1, "y")

s.replace(s.find(x),1,“y”)

To do this for the whole string, the easy thing to do would be to loop until your s.find starts returning npos. I suppose you could also catch range_error to exit the loop, but that's kinda ugly.

为了整个字符串这样做,很容易做的事情是循环到你的s。发现开始返回非营利组织。我想您也可以捕获range_error来退出循环,但这有点难看。

#6


4  

As Kirill suggested, either use the replace method or iterate along the string replacing each char independently.

如Kirill所建议的,要么使用replace方法,要么在字符串中迭代,独立地替换每个char。

Alternatively you can use the find method or find_first_of depending on what you need to do. None of these solutions will do the job in one go, but with a few extra lines of code you ought to make them work for you. :-)

或者,您可以使用find方法或find_first_of根据需要做什么。这些解决方案都不会一次性完成任务,但是需要额外的几行代码,您应该让它们为您工作。:-)

#7


3  

#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;
}

#8


3  

If you're looking to replace more than a single character, and are dealing only with std::string, then this snippet would work, replacing sNeedle in sHaystack with sReplace, and sNeedle and sReplace do not need to be the same size. This routine uses the while loop to replace all occurrences, rather than just the first one found from left to right.

如果您希望替换多个字符,并且只处理std::string,那么该代码段将工作,用sReplace替换sHaystack中的sNeedle, sNeedle和sReplace不需要相同的大小。这个例程使用while循环来替换所有的事件,而不是从左到右的第一个。

while(sHaystack.find(sNeedle) != std::string::npos) {
  sHaystack.replace(sHaystack.find(sNeedle),sNeedle.size(),sReplace);
}

#9


0  

This works! I used something similar to this for a bookstore app, where the inventory was stored in a CSV (like a .dat file). But in the case of a single char, meaning the replacer is only a single char, e.g.'|', it must be in double quotes "|" in order not to throw an invalid conversion const char.

这个工作!我在一个书店应用程序中使用了类似的东西,其中的库存存储在CSV中(比如.dat文件)。但是在单个char的情况下,意味着替换器仅是一个char,例如'|',它必须是双引号“|”,以便不抛出无效的转换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

Uncustomarily I am using CentOS currently, so my compiler version is below . The C++ version (g++), C++98 default:

通常我现在使用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.

#10


0  

If you're willing to use std::strings, you can use this sample-app's strsub function as-is, or update it if you want it to take a different type or set of parameters to achieve roughly the same goal. Basically, it uses the properties and functionalities of std::string to quickly erase the matching set of characters, and insert the desired characters directly within the std::string. Every time it does this replacement operation, the offset updates if it can still find matching chars to replace, and if it can't due to nothing more to replace, it returns the string in its state from the last update.

如果您愿意使用std::string,您可以使用这个示例应用程序的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;
}

If you don't want to rely on using std::strings as your parameters so you can pass in C-style strings instead, you can see the updated sample below:

如果您不想依赖std::字符串作为参数,那么您可以使用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;
}

#11


0  

For simple situations this works pretty well without using any other library then std::string (which is already in use).

对于简单的情况,这可以很好地运行,而不需要使用任何其他的库,然后std::string(已经在使用中)。

Replace all occurences of character a with character b in some_string:

在some_string中替换字符a与字符b的所有出现:

for (size_t i = 0; i < some_string.size(); ++i) {
    if (some_string[i] == 'a') {
        some_string.replace(i, 1, "b");
    }
}

If the string is large or multiple calls to replace is an issue, you can apply the technique mentioned in this answer: https://*.com/a/29752943/3622300

如果字符串是大的或多个调用来替换是一个问题,那么您可以应用在这个答案中提到的技术:https://*.com/a/29752943/3622300。