C 如何打破while查找循环

C++ How to break a while find loop?

本文关键字:查找 循环 while 何打破      更新时间:2023-10-16

在此循环中,我想在evert dot(。)的后面添加新行( n)。

在每个点之后添加新线时如何打破循环?

while (alltxt.find(".") != string::npos)
    alltxt.replace(alltxt.find("."), 1, ".n");

您可以使用不同的std :: string ::找到接受起始位置的超载。然后,您在发现的'.'之前开始每个搜索。

类似的东西:

std::string::size_type pos = 0;
while((pos = s.find(".", pos)) != std::string::npos)
{
    s.replace(pos, 1, ".n");
    pos += 2; // move past the dot (and the extra 'n')
}

这取决于惯用的 sigtion&测试执行分配,然后 tests 结果:

// do the assignment and then test the results
(pos = s.find(".", pos)) != std::string::npos

还要注意,与std :: string :: for for pos相当于(但不大于)s.size()

是合法的。

这是一个可能执行您想要的通用功能:

std::string& replace_all(std::string& str, const std::string& needle,
                         const std::string& replacement)
{
  auto idx = str.find(needle, 0);
  while (idx != std::string::npos) {
    str.replace(idx, needle.size(), replacement);
    idx = str.find(needle, idx + replacement.size());
  }
  return str;
}

使用从位置开始的发现过载。类似以下内容(未进行测试,只是说明性):

if(!str.empty())
{
    size_t pos = 0;
    while(true)
    {
    pos = str.find(pos, '.');
    if(std::string::npos==pos)
    break;
    str.insert(++pos, 1, 'n');
    }
    }

在the()中使用条件将要求对其进行两次检查(您绝对需要在查找后检查),这样,只有一个测试可以出现。