c++ - 在字符串中找到特定字符后,如何创建一个插入字符的循环?
问题描述
我试图创建一个循环,在输入字符串的每个周期迭代之后插入一个空格。当我使用 if 语句时,它只修改第一个实例。我不知道如何创建一个循环来检查每个时期然后插入空格。
我试图用while循环创建函数,但它一直在无限运行。
void myfunc(string &s) {
int pos = s.find('.');
if (pos != string::npos) {
pos = s.find('.', pos + 1);
s.insert(pos," ");
}
cout << s;
我希望在一个周期的迭代之后有一个空间,但遗憾的是它只在找到第一次迭代后才修改。
解决方案
您可以使用该std::find
函数而不是字符串find
函数在循环中巧妙地执行此操作。
#include <string>
#include <algorithm>
#include <cassert>
int main() {
auto s = std::string {"test.string.here." };
auto it = s.begin();
while ((it = std::find(it, s.end(), '.')) != s.end()) {
it = s.insert(it+1, ' ') + 1;
}
assert(s == "test. string. here. ");
}
推荐阅读
- javascript - 如何防止长时间运行的 HTTP 请求超时?
- javascript - 空值与jsp表单中的实际值一起插入数据库
- if-statement - 如何在 Google 表格中使用动态范围填充 VLOOKUP?
- python - Tkinter 网格方法查询。无需从函数中返回
- html - 尝试在移动设备上更新标题大小,但 CSS 没有响应。我错过了什么吗?
- vbscript - 代码不起作用 - SetDwordValue 在 vbs 中不起作用
- python - scipy ndimage 使用哪种三次样条方法进行 affine_transform?
- python-3.x - 如何通过减少循环来生成排列?
- ruby - 解析CSV文件中由分隔符分隔的每个文本的值
- python - 不了解用于测试的多个测试标记