对字符串中的单词计数
Count words in a string
我需要一些帮助来计算字符串中的单词。计算字符串s中的单词数。单词之间用空格分隔。有一个sol
istringstream iss(s);
string temp;
int words = 0;
while (iss >> temp) {
++words;
}
但是如果我们把问题改成计算字符串s中的单词数。单词之间用;分隔。或者如果我们有;或:作为分隔符。
是否可以将分隔符从空格更改为;在这个解中?
istringstream iss(s);
int words = distance(istream_iterator<string>(iss),
istream_iterator<string>());
也可以使用正则表达式:
std::regex rx("(\w+)(;|,)*");
std::string text = "this;is,a;test";
auto words_begin = std::sregex_iterator(text.begin(), text.end(), rx);
auto words_end = std::sregex_iterator();
auto count = std::distance(words_begin, words_end);
std::cout << "count: " << count << std::endl;
for(auto i = words_begin; i != words_end; ++i)
{
auto match = *i;
std::cout << match[1] << 'n';
}
输出为:
count: 4
this
is
a
test
可以使用带字符分隔符的getline
istream& std::getline (istream& is, string& str, char delim);
类似:
std::replace_if(s.begin(), s.end(), isColon, ';');
istringstream iss(s);
string temp;
int words = 0;
while (std::getline(iss,temp,';') {
++words;
}
和谓词:
bool isColon (char c) { return (c == ';'); }
一些简单的手工制作的循环:
#include <cctype>
#include <iostream>
int main() {
unsigned result = 0;
std::string s = "Hello world";
std::string::const_iterator c = s.begin();
while(c != s.end() && std::isspace(*c)) ++c;
while(c != s.end() && ! std::isspace(*c)) {
++result;
while(++c != s.end() && ! std::isspace(*c));
if(c != s.end()) {
while(std::isspace(*c)) ++c;
}
}
std::cout << "Words in '" << s << "': " << result << 'n';
}
相关文章:
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- C++-字符串是否包含一个带有简单循环的单词
- 在C++中查找(奇怪的)字符串中的单词
- 输出返回编号。等于输入字符串的单词的字符串数
- 将 2 个单词与字符串分隔开
- 包含换行符分隔的单词的文件和C++中这些单词的字符串向量的大小是否相同?
- 如何输入每个单词在字符串数组中的句子,直到用户按Enter键
- 提取第二个单词.解析字符串(C )
- 分类包含数字和单词的字符串向量
- C 输入多个单词要字符串
- 用输入中给出的单词填充字符串
- 忽略包含特殊单词的字符串(月)
- 如何读取特定单词的字符串并计算发现的时间
- C++一次打印一个单词的字符串,计算字符数和字符数
- 为什么我的 forloop 在我的 lexical_words 函数中没有将字符串数组('keyWords")中的单词与字符串迭代器中的单词进行比较?
- 使用指针按单词反转字符串
- 按分度计C++字符串到字符串数组
- 分析单词的字符串
- 取一个包含任意数量单词的字符串,并将这些单词存储在不同的字符串变量中