Computer Science – 11.1 Programming Basics | e-Consult
11.1 Programming Basics (1 questions)
Login to see all questions.
Click on a question to view the answer
Here's a C++ solution:
#include
#include
#include
int countWords(const std::string& inputString) {
std::stringstream ss(inputString);
std::string word;
int wordCount = 0;
if (inputString.empty() || (inputString.findfirstnot_of(" ") == std::string::npos)) {
return 0; // Handle empty or all-space strings
}
while (std::getline(ss, word, ' ')) {
if (!word.empty()) { // Avoid counting empty strings resulting from multiple spaces
wordCount++;
}
}
return wordCount;
}
int main() {
std::string input1 = "apple,banana,orange";
std::cout
Explanation:
- The countWords() function takes a string as input.
- It uses a stringstream to parse the input string.
- It handles the cases where the input string is empty or contains only spaces by returning 0.
- It iterates through the string, extracting words separated by spaces using std::getline().
- It increments the wordCount for each non-empty word.