c++ - 由多个分隔符分割 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++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
您必须进一步调整正则表达式以删除空格。
推荐阅读
- oracle - SSIS 视觉工作室 2015 甲骨文 - 坏
- java - Oracle JDBC 仅使用 FETCH NEXT n ROWS 引发 ORA-00933
- c# - 串行端口不适用于 .Net Core 3.0 中的 arm64 - System.IO.Ports.SerialStream.set_DtrEnable(布尔值)的参数无效
- c - 如何将字符串的每一行保存到C中的新字符串中?
- java - 映射到 hbm.xml 文件时无法提取 ResultSet
- angular - 如何以角度编辑过滤器?
- django - 如何在chart.js模板中使用for循环标签
- python - 编写一个函数 printWithAge,它接受一个文件名和一个年龄作为参数,并打印出该年龄的每个玩家的名字
- docker - 如何为在 docker 容器内运行的操作系统启用远程桌面共享(如 VNC 服务器)
- java - HERE Maps Android:在避开特定区域的同时计算方向