首页 > 解决方案 > 在字符串中找到特定字符后,如何创建一个插入字符的循环?

问题描述

我试图创建一个循环,在输入字符串的每个周期迭代之后插入一个空格。当我使用 if 语句时,它只修改第一个实例。我不知道如何创建一个循环来检查每个时期然后插入空格。

我试图用while循环创建函数,但它一直在无限运行。

void myfunc(string &s) {

int pos = s.find('.');
if (pos != string::npos) {
pos = s.find('.', pos + 1);
s.insert(pos,"  ");


} 
cout << s;

我希望在一个周期的迭代之后有一个空间,但遗憾的是它只在找到第一次迭代后才修改。

标签: c++stringloops

解决方案


您可以使用该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. ");
}

推荐阅读