将一个字符替换为字符串中更多数量的字符,而不删除C++中的其他字母
To replace one char by a higher amount of chars within a string, without deleting other letters in C++
我想替换字符串中的字符'ü'(如果找到(。我的代码替换了ü
,但也删除了字符串中的其他字母。
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
}
相关文章:
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 为什么 Serial.println(<char[]>);返回随机字符?
- 我的字符计数代码计算错误.为什么
- 字符串-C++后显示的随机字符
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 如何在C++中从字符串中分割字符
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 指向指向字符数组的指针数组的指针
- 如何用转义符替换字符串中的所有特殊字符
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 比较字符数组
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++中无符号字符溢出
- 使用无符号字符数组有效存储内存