gpt4 book ai didi

C++ 在 char 上正确拆分文本

转载 作者:行者123 更新时间:2023-11-28 00:47:29 24 4
gpt4 key购买 nike

我是 C++ 的新手,我想我在这段代码的某处犯了一个小错误。到目前为止我没能发现它。我希望你能帮助我,并告诉我它是如何/在哪里/为什么是错误的?非常感谢。

代码:

std::vector<std::string> spliter(const std::string& s, char delimiter)
{
std::vector<std::string> result;

size_t start = 0;
for(std::size_t i = 0; i != std::string::npos; i = s.find(delimiter,start))
{
result.push_back( s.substr(start,i-start) );
start = i+1;
}
iprintf("\x1b[2J");
printf("\x1b[4;0HDone Splitting Text.");
swiWaitForVBlank();
return result;
}

给出的参数:s = "$ 00-000 SS ''Prologue'' CF N00-001 V 1 MP 20"delimiter = ' '(一个空格)

预期结果:

result[0] = $
result[1] = 00-000
result[2] = SS
etc.

当前错误结果:

result[0] = 
result[1] =
result[2] = 00-000
etc.

非常感谢任何帮助!

最佳答案

我相信问题出在循环中。你从 0 开始,你推送的第一件事是从 0 到 0。

    size_t start = 0;
for(std::size_t i = 0; i != std::string::npos; i = s.find(delimiter,start))
{
result.push_back( s.substr(start,i-start) );
start = i+1;
}

相反,如果您从 s.find(delimiter, start) 开始 i,它应该可以工作。 Example here..

关于C++ 在 char 上正确拆分文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15735360/

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