首页 > 解决方案 > 由多个分隔符分割 C++

问题描述

我正在尝试用标点符号 ( ., ?, !) 将句子分开。我在 StackOverflow 上找到了一种通过一个分隔符分隔字符串的方法,但是我无法找到一种方法来一次基于多个分隔符分隔字符串。这是我到目前为止的代码:

void chopSentences(std::string new_sentences, std::vector<std::string> sentences) {
    size_t pos = 0;
    std::string token;
    std::string delimiter = ".";
    while ((pos = new_sentences.find(delimiter) != std::string::npos)) {
        token = new_sentences.substr(0, pos);
        sentences.push_back(token);
        new_sentences.erase(0, pos + delimiter.length());
    }
}

关于如何使它成为多个分隔符的任何想法?

标签: c++parsing

解决方案


如果您使用的是 C++11 或更高版本,则可以使用std::regex_iterator

std::string const s{"Hello, Johnny! Are you there?"};`
 
std::regex words_regex("[^[:punct:]\\?]+");
auto words_begin = 
    std::sregex_iterator(s.begin(), s.end(), words_regex);
auto words_end = std::sregex_iterator();
 
std::cout << "Found " 
          << std::distance(words_begin, words_end) 
          << " words:\n";
 
for (std::sregex_iterator i = words_begin; i != words_end; ++i) {
    std::smatch match = *i;                                                 
    std::string match_str = match.str(); 
    std::cout << match_str << '\n';
}

然后打印输出是:

Found 3 words:
Hello
 Johnny
  Are you there

您必须进一步调整正则表达式以删除空格。


推荐阅读