counting number of words in a string

Viewed 235

I'm a newbie here. I'm trying to make a function to count the words from a string, but my normal ape brain doesn't allow me to think further. Can you guys take a look at my work and give me some guidance?

int numWords(string wordnum, ){
    int counting = 0;
    int space = 0;
    
    while(int i<wordnum.length()){
        
        if(wordnum[i] == " " && wordnum[i] == "\n"){
            space=0;
        }
        else if(space ==0){
            space = 1;
            counting++;  
        }
3 Answers

If the words are separated by whitespace, simply use std::stringstream and a while loop:

#include <sstream>
#include <string>
#include <iostream>

int numWords(std::string wordnum)
{
  int counting = 0;
  std::string word;
  std::stringstream strm(wordnum);

  while (strm >> word)
    ++counting;
  return counting;
}

int main()
{
   std::cout << numWords("The number of words");
}

Output:

4

It is much better to use a for loop for this to go through the code instead of a while loop, because you are incrementing an index every time you iterate through the loop. Another mistake is that you used the "" parantheses for seeing if the indexed character in the loop is a newline or space. This doesnt work as if you index a string's character it will return a char instead of a char* or string. The '' parantheses are for chars. I have seen in the comments that you also wanted to add input, so as an extra feature, i added that with the getline command. I'd recommend for you to read a basic C++ book/tutorial on how to get started, because your code has alot of syntax mistakes.

#include <iostream>
#include <string>

using namespace std;

int numWords(string wordnum) {
    int counting = 0;
    int space = 0;
    bool waiting = false;
    if(wordnum[0] != ' ' && wordnum[0] != '\n') {
        space++;
    }
    for(counting = 0; counting < wordnum.length(); counting++) {
        if(wordnum[counting] == ' ' || wordnum[counting] == '\n') {
            waiting = true;
        }
        if(waiting == true && wordnum[counting] != ' ' && wordnum[counting] != '\n') {
            waiting = false;
            space++;
        }
    }
    return space;
}

int main() {
    string example;
    getline(cin, example);
    cout << "Number of words: " << numWords(example) << endl;
} 

There are really many different possible solutions.

One idea is, to see a word as an element in a container, which is a string in this case. And with iterators, we can iterate over elements in a container.

One good iterator to iterate over elements in a string is the std::sregex_token_iterator. Here you can define a pattern for an element that you want to iterate over using a std::regex.

And with the help of std::distance, you can measure the number of elements in the range of 2 iterators.

All this glued together will give you a typical one liner:

#include <iostream>
#include <string>
#include <regex>
#include <algorithm>
#include <iterator>

const std::regex re{ R"(\w+)" };
const std::string text{ R"(Lorem ipsum dolor sit amet, consetetur sadipscing elitr, 
sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, 
sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. 
Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. 
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod 
tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero 
eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea 
takimata sanctus est Lorem ipsum dolor sit amet.)" };

int main() {

    // Output the number of words
    std::cout << "\n\nNumber of words in text: "

        << std::distance(std::sregex_token_iterator(text.begin(), text.end(), re), {})

        << "\n\n";

    return 0;

}
Related