什么是有效的方法来取代一个字符的所有出现与另一个字符在std::字符串?


当前回答

为了完整起见,下面是如何使用std::regex来实现它。

#include <regex>
#include <string>

int main()
{
    const std::string s = "example string";
    const std::string r = std::regex_replace(s, std::regex("x"), "y");
}

其他回答

Std::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'
}

正如Kirill建议的那样,要么使用replace方法,要么沿着字符串迭代,单独替换每个字符。

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

如何替换任何字符串与任何字符串仅使用良好的旧C字符串函数?

char original[256]="First Line\nNext Line\n", dest[256]="";
char* replace_this = "\n"; // this is now a single character but could be any string
char* with_this = "\r\n"; // this is 2 characters but could be of any length

/* get the first token */
char* token = strtok(original, replace_this);

/* walk through other tokens */
while (token != NULL) {
    strcat(dest, token);
    strcat(dest, with_this);
    token = strtok(NULL, replace_this);
}

Dest现在应该有我们要找的东西了。

这是我滚动的一个解决方案,在最大的DRI精神。 它将在sHaystack中搜索sNeedle并将其替换为sReplace, nTimes如果不为0,否则所有的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;
}
#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;
}