用两个字符分隔字符串

时间:2014-08-26 11:10:58

标签: c++

我想逐个字符地分开","或";"。

std::string input = "abc,def;ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) { //how to add here ";"?
    std::cout << token << '\n';
}

3 个答案:

答案 0 :(得分:3)

使用Boost Tokenizer library

boost::char_separator<char> sep(",;");
boost::tokenizer<boost::char_separator<char>> tokens(input, sep);

答案 1 :(得分:1)

旧的风格怎么样?

std::string string = "abc,def;ghi";
std::vector<std::string>strings;
std::string temp;
for(int i=0; i < string.length(); i++)
{
    if(string[i] == ',' || string[i] == ';')
    {
        strings.push_back(temp);
        temp.clear();
    }
    else
    {
        temp += string[i];
    }
}
strings.push_back(temp);

live demo

答案 2 :(得分:0)

在C库的string.h中使用strsep,你可以这样做:

std::string input = "abc,def;ghi";
const char* ss = intput.c_str();
const char token[] = ",;";

for (const char* part; (part = strsep(&ss, token)) != NULL;) {
    std::cout<< part << std::endl;
}