对字符串中的单词计数

Count words in a string

本文关键字:单词计 字符串      更新时间:2023-10-16

我需要一些帮助来计算字符串中的单词。计算字符串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';
}