C++ C++;如何打破一段时间的循环?
在这个循环中,我想在evert dot(.)后面添加新行(\n) 在每个点后添加新行时,如何打破循环C++ C++;如何打破一段时间的循环?,c++,string,loops,while-loop,find,C++,String,Loops,While Loop,Find,在这个循环中,我想在evert dot(.)后面添加新行(\n) 在每个点后添加新行时,如何打破循环 while (alltxt.find(".") != string::npos) alltxt.replace(alltxt.find("."), 1, ".\n"); 您可以使用接受起始位置的不同重载。然后在找到的“.之前开始每次搜索 大概是这样的: std::string::size_type pos = 0; while((pos = s.find(".", pos)) !=
while (alltxt.find(".") != string::npos)
alltxt.replace(alltxt.find("."), 1, ".\n");
您可以使用接受起始位置的不同重载。然后在找到的
“.
之前开始每次搜索
大概是这样的:
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')
}
这依赖于惯用的赋值和测试,它执行赋值,然后测试结果:
// do the assignment and then test the results
(pos = s.find(".", pos)) != std::string::npos
还要注意的是,
pos
等于(但不大于)s.size()
是合法的。您可以使用不同的重载来接受起始位置。然后在找到的“.
之前开始每次搜索
大概是这样的:
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')
}
这依赖于惯用的赋值和测试,它执行赋值,然后测试结果:
// do the assignment and then test the results
(pos = s.find(".", pos)) != std::string::npos
还要注意的是,
pos
等于(但不大于)s.size()是合法的。请使用从某个位置开始的查找重载。类似于以下内容(未经测试,仅用于说明):
在while()中使用条件需要检查两次(您绝对需要在查找之后进行检查),这样,只有一个测试结果可能不同。使用从某个位置开始的查找重载。类似于以下内容(未经测试,仅用于说明):
在while()中使用条件需要检查两次(您绝对需要在查找后进行检查),这样,只有一个测试结果可能会有所不同。下面是一个通用函数,它可以执行您想要的操作:
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;
}
下面是一个通用函数,它可以实现您想要的功能:
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;
}
您需要记录找到点的位置,然后从那里开始下一次搜索。@问题是您正在将第一个。
替换为。\n“
,然后从一开始就重新开始搜索。然后,您每次都会找到相同的点。@因此,您的问题并不是跳出循环。如果循环的主体是正确的,它将自动执行该操作。您的问题是算法的逻辑不正确。提示:std::string::find
接受启动position@Thesar您还可以使用类似'std::replace(s.begin(),s.end(),“x”,“y”)`您需要记录找到点的位置,然后从那里开始下一次搜索。@问题是您正在将第一个。
替换为。\n“
,然后从一开始就重新开始搜索。然后,您每次都会找到相同的点。@因此,您的问题并不是跳出循环。如果循环的主体是正确的,它将自动执行该操作。您的问题是算法的逻辑不正确。提示:std::string::find
接受启动position@Thesar您还可以使用类似'std::replace(s.begin(),s.end(),“x”,“y”)`所以这意味着我们在pos后搜索,我们分配字符“.”,每当我们找到它,我们就用2个字符替换它。\n然后通过向pos添加“2”跳过它们?我只是想了解一下逻辑,以便下次我能记住它。谢谢大家!@是的,正是这样。我不得不考虑另一个我想实施的问题。这也许也能解决问题。要使每一新行中的第一个字母大写,请使用此重载将\n之后的第一个字母大写。你认为它在逻辑上可行吗?@是的,你可以,但同时更改大写字母可能更有效。您可以在pos+=2之后添加该代码
搜索下一个字母。这意味着我们在pos后搜索,我们分配字符“.”,无论何时找到它,我们都用2个字符替换它。\n然后通过向pos添加“2”跳过它们?我只是想了解一下逻辑,以便下次我能记住它。谢谢大家!@是的,正是这样。我不得不考虑另一个我想实施的问题。这也许也能解决问题。要使每一新行中的第一个字母大写,请使用此重载将\n之后的第一个字母大写。你认为它在逻辑上可行吗?@是的,你可以,但同时更改大写字母可能更有效。您可以在pos+=2之后添加该代码
搜索下一个字母。