拆分多个字符串中的字符串,并在一行中包含多个分隔符

时间:2014-11-28 14:52:03

标签: c++ string split tokenize

我期待最好的字符串标记器实现。我已经看到很多实现,但其中一些不能连续使用多个分隔符。我可以自己做,但我不知道一些已经存在的功能,所以也许它已经以正确和快速的方式实现。
我需要拆分例如这样的字符串

  

“This__should _______是____ split_into ____ 7个___字符串”

在这种情况下,分隔符是下划线。 什么是最正确和最优雅的方式?

修改

对不起,我没有提到。我只需要使用默认库,而不需要像boost和其他类似的外部驱动程序。

2 个答案:

答案 0 :(得分:1)

使用有用的提升字符串算法:

std::vector<std::string> words;
std::string sentence = "This__should_______be____split_into____seven___strings";
boost::split(words, sentence, boost::is_any_of("_"));
words.erase(
    std::remove_if(
        words.begin(), words.end(), 
            [](const std::string &s){return s.empty();}));

DEMO

修改:根据更新的要求:

std::vector<std::string> words;
std::string word = "";
char prev = '\0';
std::string sentence = "This__should_______be____split_into____seven___strings";
for (char c : sentence)
{
    switch (c)
    {
    case '_':
    {
        if (prev != '_')
        {
            words.push_back(word);
            word = "";
            prev = '_';
        }
        break;
    }
    default:
    {
        word += c;
        prev = c;
        break;
    }
    };
}
if (!word.empty())
{
    words.push_back(word);
}

DEMO

答案 1 :(得分:0)

简单的C标记生成器,经过测试并使用给定的字符串。您也可以在C ++中使用此方法。 注意:它只适用于以空字符结尾的字符串。

char *text = "This__should_______be____split_into____seven___strings";
char *p = text;
char buf[20];
while (*p != '\0')
{
    char *start;
    int len;

    while (*p != '\0' && *p == '_')
        ++p;

    if (*p == '\0')
        break;

    start = p;
    while (*p != '\0' && *p != '_')
        ++p;

    len = p - start;
    strncpy(buf, start, len);
    buf[len] = '\0';
    printf ("%s\n", buf);
    buf[0] = '\0';    
}
相关问题