计算字符串中的单词

时间:2014-03-14 13:37:55

标签: c++

我需要帮助计算字符串中的单词。 计算字符串s中的单词数。 单词由空格分隔。 有一个解决方案

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>()); 

3 个答案:

答案 0 :(得分:3)

您可以将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 == ';'); }

答案 1 :(得分:3)

也可以使用正则表达式:

   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

答案 2 :(得分:1)

一些简单的手工制作的循环:

#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';
}
相关问题