gpt4 book ai didi

c++ - 如何从字符串中删除所有双空格

转载 作者:太空狗 更新时间:2023-10-29 23:35:05 24 4
gpt4 key购买 nike

我试图从我的字符串中删除所有双空格,以便只保留一个空格:

while  (doublespace != -1) {
kstring.replace(doublespace, 1, " ") ;
doublespace = kstring.find_first_of(" ") ; }

它找到第一个双空格,触发 while 语句。然后它获取第一个空格,将其加 1 并将两个空格设置为一个空格。然后它再次检查。

问题是循环永远不会结束 - 例如,如果我输入“hello”,doubleSpace 将永远不会设置为 -1。

最佳答案

std::string::find_first_of 只搜索直到找到输入字符串中的一个字符,所以当你传递它时 "",它只会有效地搜索 "" - 请参阅文档 here :

Searches the string for the first character that matches any of the characters specified in its arguments.

你应该使用 std::string::find相反,它搜索整个子字符串的第一个实例:

Notice that unlike member find_first_of, whenever more than one character is being searched for, it is not enough that just one of these characters match, but the entire sequence must match.

您还仅将第一个空格替换为空格 (sString.replace(doubleSpace, 1, ""),这意味着您的输出仍将包含双空格。只需使用 std::string::erase相反,只删除第一个空格。


这意味着您的代码片段应该更像:

std::size_t doubleSpace = sString.find("  ");
while (doubleSpace != std::string::npos)
{
sString.erase(doubleSpace, 1);
doubleSpace = sString.find(" ");
}

关于c++ - 如何从字符串中删除所有双空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48029688/

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