将一个字符替换为字符串中更多数量的字符,而不删除C++中的其他字母

To replace one char by a higher amount of chars within a string, without deleting other letters in C++

本文关键字:字符 C++ 删除 其他 一个 替换 字符串      更新时间:2023-10-16

我想替换字符串中的字符'ü'(如果找到(。我的代码替换了ü,但也删除了字符串中的其他字母。

if (word.find('ü') != string::npos) 
{
word.replace(word.find('ü'), 'ü', "ue");
}

不是单行,但erase后跟insert就足够清楚了。

size_t x = word.find('ü');
while (x != string::npos)
{
word.erase(x, 1);
word.insert(x, "ue");
x = word.find('ü');
}

你可以找到ü的位置,从索引0开始,直到字符串的末尾,每当找到时,使用找到的位置和你想在给定字符串中找到的字符串长度的信息将其替换为ue

如下所示:在此处查看直播

#include <iostream>
#include <string>
#include <algorithm>
#include <cstddef>
int main()
{
std::string word("Herr Müller ist ein König.");
std::string findThis = "ü";
std::string replaceWith = "ue";
std::size_t pos = 0;
while ((pos = word.find(findThis, pos)) != std::string::npos)
{
word.replace(pos, findThis.length(), replaceWith);
pos += replaceWith.length();
}
std::cout << word << std::endl;
return 0;
}

输出:

Herr Mueller ist ein König.

如果使用 boost 是一种选择,您可以执行以下操作

#include <boost/algorithm/string.hpp>
int main()
{
std::string str("Herr Müller ist ein König.");
boost::replace_all(str, "ü", "ue");
std::cout << str << std::endl;
return 0
}