Open ooolky opened 6 months ago
std::string::size_type n = 0; while ((n = result.find("main", n)) != std::string::npos) { result.replace(n, 4, "sub"); n += 3; // 移动到替换字符串之后,避免无限循环 }
n
size_type
while
find
std::string::npos
replace
n
是一个size_type
变量,用于记录当前找到的 "main" 的位置。while
循环和find
方法从位置n
开始查找 "main"。find
找到 "main",它会返回其在字符串中的位置。std::string::npos
。replace
方法从位置n
开始替换 4 个字符("main" 的长度)为 "sub"。n
增加 3,即 "sub" 的长度。这样做是为了在下一次迭代时跳过刚替换的部分,防止在新字符串中重新查找 "main",从而避免无限循环。