gpt4 book ai didi

c++ - 将 while 循环转换为 do while 循环

转载 作者:行者123 更新时间:2023-11-30 01:50:20 24 4
gpt4 key购买 nike

这是一个用父字符串中的另一个词(strng)替换特定词(字符串)的所有实例的函数。

void clean(std::string &s,const std::string oldVal,const std::string newVal){
std::string::size_type pos = 0;

while((pos = s.find(oldVal,pos)) != std::string::npos){
s.replace(pos,oldVal.size(),newVal);
pos += newVal.size();
}
}

我是 C++ 的新手,我发现 while 条件有点难以理解。所以我想到了让这段代码更具可读性。我试着把它变成一个 do while 循环。然而,程序崩溃了。抛出超出范围的异常。
我的代码有什么问题?我使用相同的字符串来检查这两个函数。

void clean2(std::string &s,const std::string oldVal,const std::string newVal){
std::string::size_type pos = 0;
do{
pos = s.find(oldVal,pos);
s.replace(pos,oldVal.size(),newVal);
pos += newVal.size();
}while(pos != std::string::npos);
}

最佳答案

这种情况

pos != std::string::npos

你必须在声明后检查

pos = s.find(oldVal,pos);

否则你可以使用无效的 pos 值。

所以在这种情况下,while 循环看起来比 while 循环更好。:)

您可以使用 for 循环重写该函数,而不是将 while 循环替换为 do-while 循环。例如

void clean(std::string &s,const std::string oldVal,const std::string newVal)
{
for ( std::string::size_type pos = 0;
( pos = s.find( oldVal, pos ) ) != std::string::npos;
pos += newVal.size() )
{

s.replace( pos, oldVal.size(), newVal );
}
}

关于c++ - 将 while 循环转换为 do while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27542445/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com