【问题标题】:Split string in a multiple strings with multiple delimeters in a row [closed]在具有多个分隔符的多个字符串中拆分字符串 [关闭]
【发布时间】:2014-11-28 14:52:03
【问题描述】:

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

“这__应该是____split_into____seven___strings”

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

编辑

对不起,我没有提到。我只需要使用默认库来执行此操作,而无需像 boost 和其他不同的外部库。

【问题讨论】:

标签: c++ string split tokenize


【解决方案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

【讨论】:

  • 我已经更新了我的问题,请看一下
【解决方案2】:

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

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';    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-21
    相关资源
    最近更新 更多