How to check if two strings have the same number of words in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <sstream> 

int countWords(const std::string& str) {
    std::stringstream ss(str);  
    std::string word; 
    
    int count = 0; 
    while (ss >> word) 
        count++;
          
    return count; 
}

bool haveSameNumberOfWords(const std::string& str1, const std::string& str2) {
    return countWords(str1) == countWords(str2);
}

int main() {
    std::string str1 = "C++ is a general purpose programming language "; 
    std::string str2 = "created by Danish computer scientist Bjarne Stroustrup";

    if (haveSameNumberOfWords(str1, str2)) {
        std::cout << "yes";
    } else {
        std::cout << "no";
    }
}

 
 
/*
run:
 
yes
 
*/

 



answered May 8, 2024 by avibootz
...