替换字符串中的3个或更多字符出现
Replace 3 or more occurrences of character within string
我想在std :: string中找到3个或多个出现以替换。
例如:
std::string foo = "This is annn test";
std::string bar = "This is annnn test";
std::string baz = "This is annnnn test";
std::string boo = "This is annnnnn test";
// ... etc.
应该将所有全部转换为:
std::string expectedResult = "This is ann test";
香草stl将不胜感激(如果可能
这应该找到连续 n并替换它们:
size_type i = foo.find("nnn");
if (i != string::npos) {
size_type j = foo.find_first_not_of('n', i);
foo.replace(i, j - i, "nn");
}
编写一个函数来处理您对修改感兴趣的每个字符串:
一个时间读取每个字符串一个字符。跟踪2个字符变量:a和b。对于您阅读的每个字符c,请执行:
if ( a != b ) {
a = b;
b = c;
} else if ( a == b ) {
if ( a == c ) {
// Put code here to remove c from your string at this index
}
}
我不是100%确定您是否可以直接使用STL来完成您的要求,但是您可以看到此逻辑并不是要实现的代码太多。
您可以使用查找和替换。(这将替换" n n n ..." ->" n n")。您可以将位置传递给字符串::查找,以便您不必再次搜索字符串的开始(优化)
int pos = 0;
while ((pos = s.find ("nnn", pos)) != s.npos)
s.replace (pos, 3, "nn", 2);
这将替换" n n n n n .." ->" n"
int pos = 0;
while ((pos = s.find ("nn", pos)) != s.npos)
s.replace (pos, 2, "n", 1);
相关文章:
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 将 NULL 与 C 的字符* 字符串一起使用
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 无法将常量字符字符串传递给模板类
- 如何组合一个宽字符字符串,中间插入一些空字符
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 从给定索引返回子字符字符串的函数
- 字符 [](c 字符串)的初始化标准
- 如何将字符字符串用作数学运算符
- 将 Unicode 字符/字符串写入文件
- C++,字符* 字符串修改
- 如何有效地用不同的整数元素替换字符字符串的元素
- C++:如果我们在字符串中添加一些整数,为什么它会从开头删除该数量的字符?(字符串 + 整数)
- strcpy正在复制sth字符i字符串.如何解决此错误
- 在C++中将双精度转换为字符*/字符串
- C 中的宽字符字符串
- 如何提取C 中的字符/字符串之间的字符串
- 无法将字符/字符串转换为int
- 带有指针的反转字符字符串
- 反转字符串中的 n 个字符(字符串中没有空格),而不使用 c++ 中的内置函数