Count words in a string

后端 未结 3 1388
予麋鹿
予麋鹿 2021-01-27 10:53

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


        
相关标签:
3条回答
  • 2021-01-27 11:23

    You can use getline with character delimiter.

    istream& std::getline (istream& is, string& str, char delim);
    

    Something like:

    std::replace_if(s.begin(), s.end(), isColon, ';');
    istringstream iss(s);
    string temp;
    int words = 0;
    while (std::getline(iss,temp,';') {
      ++words;
    }
    

    And the predicate:

    bool isColon (char c) { return (c == ';'); }
    
    0 讨论(0)
  • 2021-01-27 11:28

    Some simple hand crafted loops:

    #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';
    }
    
    0 讨论(0)
  • 2021-01-27 11:40

    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';
       }
    

    The output is:

    count: 4
    this
    is
    a
    test
    
    0 讨论(0)
提交回复
热议问题