c++ - 拆分 C++ 字符串 boost ?

标签 c++ string boost split

给定一个字符串,例如“John Doe,USA,Male”,我将如何使用逗号作为分隔符来拆分字符串。目前我使用的是 boost 库,我设法拆分,但白色间距会导致问题。

例如,上面的字符串一旦被拆分成一个 vector ,就只包含“John”而不包含其余部分。

更新

这是我目前使用的代码

    displayMsg(line);   
    displayMsg(std::string("Enter your  details like so David Smith , USA, Male OR q to cancel"));
    displayMsg(line);

    std::cin >> res;    
    std::vector<std::string> details;
    boost::split(details, res , boost::is_any_of(","));

// If I iterate through the vector there is only one element "John" and not all ?

迭代后我只得到名字而不是完整的细节

最佳答案

实际上,您可以在没有 boost 的情况下做到这一点。

#include <sstream>
#include <string>
#include <vector>
#include <iostream>

int main()
{
    std::string res = "John Doe, USA, Male";
    std::stringstream sStream(res);
    std::vector<std::string> details;
    std::string element;
    while (std::getline(sStream, element, ','))
    {
        details.push_back(element);
    }

    for(std::vector<std::string>::iterator it = details.begin(); it != details.end(); ++it)
    {
        std::cout<<*it<<std::endl;
    }
}

关于c++ - 拆分 C++ 字符串 boost ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20916232/

相关文章:

c++ - 如何在 C++ 中处理大小为 1,000,000,000 的数组?

c++ - 代码信息

c++ - 使用可变范围时,循环未矢量化

c++ - 比较 std::string 和 C 样式字符串文字

c - 使用指针反转字符串

c++ - 使用 boost/std 库解析带时区的日期

c++ - OpenCV houghcircles 没有检测到任何 C++

javascript - 查找并替换字符串中第 n 次出现的 [bracketed] 表达式

perl - 在 Perl 中,如何只替换字符串的第一个字符?

c++ - 将 boost::shared_array<void> 转换为 boost::shared_array<int>