计算字符串中的单词 [英] Count words in a string

查看:57
本文介绍了计算字符串中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要som帮助来计算字符串s中的单词.计算字符串s中的单词数.单词之间用空格隔开.有溶胶

I need som help with counting words in a string s. count the number of words in a string s. Words are separated by whitespace. Has a sol

istringstream iss(s);
string temp;
int words = 0;
while (iss >> temp) {
++words;
}

但是,如果我们将问题更改为计算字符串s中的单词数.单词之间用;分隔.或者如果我们有;或:作为分隔符.

But if we change the question to count the number of words in a string s. Words are separated by ;. or if we have ; or : as separator .

是否可以将定界符从空白更改为;在这种解决方案中?

Is it possible do change the delimiter from whitespace to ; in this solution?

istringstream iss(s);
int words = distance(istream_iterator<string>(iss),
istream_iterator<string>()); 

推荐答案

还可以使用正则表达式:

It is also possible to use regular expressions:

   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

这篇关于计算字符串中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆