Count words in a string

后端 未结 3 1391
予麋鹿
予麋鹿 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: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
    

提交回复
热议问题