gpt4 book ai didi

c++ - 将字符串分解为单独的元素

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:38:26 25 4
gpt4 key购买 nike

我正在尝试编写一种算法,该算法将接受一个字符串并找到其中的各个单词,然后将该单词放入一个 vector 中。

void setChar(string s)
{
{
int i = 0;


while(i != s.size())
{

while( i != s.size() && isspace(s[i]))
i++;

int j = i;

while(j != s.size() && !isspace(s[j]))
j++;

if(i != j)
{

words.push_back(s.substr(i, j));
cout<<"Successfully stored the word "<<s.substr(i, j)<<endl;
i = j;
}

}
return;
}
}

算法运行,但给出了奇怪的结果。当我输入字符串“The turtle is very happy”时,我得到:

Successfully stored the word the

Successfully stored the word turtle is

Successfully stored the word is very happy

Successfully stored the word very happy

Successfully stored the word happy

我试过调试它,但一切看起来都很好。我跟踪 i/j 变量,它们正在为子字符串找到正确的索引。关于为什么我会得到这些结果的任何想法?

最佳答案

words.push_back(s.substr(i, j-i));
cout<<"Successfully stored the word "<<s.substr(i, j-i)<<endl;

这是你的错误。你找到了正确的位置,但你得到了错误的子字符串。获取子串时将 j 改为 j-i。

关于c++ - 将字符串分解为单独的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22368804/

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