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

标签 c++ vector split delimiter

我是 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/

相关文章:

c++ - 从二维 vector 中分解出一个 vector

c++ - C++中的分页效果是什么?

arrays - 两个数组 LISP 的两个值之和

c# - string.Split 忽略分隔符之间的空值

java - 将文件输入以逗号分割成Java数组,并重新写入文件

c# - 根据关键字剪切音频文件

c++ - 是否 = 在 lambda 的捕获列表中捕获 this 指针

c++ - 在 CodeBlocks 中设置 OpenGL

c++ - 是否可以使用未定义为 const 的工厂方法来定义 const 成员?

python - 每第n个字符拆分字符串?