How to count words in a string with C++

3 Answers

0 votes
#include <iostream>
#include <sstream>
#include <string>
 
int countWords(const std::string& s) {
    std::istringstream stream(s);
    std::string word;
    int count = 0;
 
    while (stream >> word) {
        count++;
    }
 
    return count;
}
 
int main() {
    std::string input = "C++ string parsing";
    int wordCount = countWords(input);
 
    std::cout << "Word count: " << wordCount << std::endl;
}
 
 
  
/*
run:
  
Word count: 3
  
*/

 



answered Feb 25, 2017 by avibootz
edited Nov 1, 2025 by avibootz
0 votes
#include <iostream>
#include <string>
#include <sstream>
#include <iterator>
#include <vector>
 
using std::string;
using std::vector;
 
int countWords(string s) {
    std::istringstream iss(s);
    
    vector<string> tokens{ std::istream_iterator<string>{iss},
                           std::istream_iterator<string>{} };
 
    return tokens.size();
}
 
int main()
{
    string s = "C++ string parsing";
 
    std::cout << countWords(s) << std::endl;
}
 

/*
run:
 
5
 
*/

 



answered Feb 25, 2017 by avibootz
edited Nov 1, 2025 by avibootz
0 votes
#include <iostream>
#include <sstream>
 
int countWords(const std::string& s) {
    std::stringstream ss(s);  
    std::string word; 
    
    int count = 0; 
    while (ss >> word) {
        count++;
    }

    return count;
}
 
int main() {
    std::string input = "C++ string parsing";
    int wordCount = countWords(input);
 
    std::cout << "Word count: " << wordCount << std::endl;
}
 
 
  
/*
run:
  
Word count: 3
  
*/

 



answered Nov 1, 2025 by avibootz
...