Count words in a string

后端 未结 3 1402
予麋鹿
予麋鹿 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 == ';'); }
    

提交回复
热议问题