HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppModerate

Number of words in a string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
wordsnumberstring

Problem

I wrote this pretty simple program (it's an exercise from a book). It counts the words in a simple string. The book is a very old one (I think it's from 2003) and uses char arrays. Because of this, I don't know if this solution is a proper one or not.

Can you tell me whether it is okay or not?

#include 

int main()
{
    int count_words(std::string);

    std::string input_text;
    std::cout<< "Enter a text: ";
    std::getline(std::cin,input_text);

    std::cout << "Number of words: " << count_words(input_text) << std::endl;
    return 0;
}
int count_words(std::string input_text)
{
    int number_of_words = 1;
    for(int i = 0; i < input_text.length();i++)
        if(input_text[i] == ' ')
            number_of_words++;
    return number_of_words;
}

Solution

-
Prefer std::size_t for the word count and count_words()'s return type. Also prefer std::string::size_type for the loop counter (when using indices is needed).

-
count_words()'s parameter should be passed by const& since it's not being modified:

std::size_t count_words(std::string const& input_text) {}


-
count_words() has a problem. If I press ENTER without typing anything, it gives me 1. To fix this, return 0 if the string is empty:

if (input_text.empty()) return 0;


-
In the for-loop, prefer std::isspace for detecting whitespace.

-
Prefer iterators over indices for std::string:

for (auto iter = input_text.cbegin(); iter != input_text.cend(); ++iter)
{
    if (*iter == isspace)
    {
        number_of_words++;
    }
}


If you have C++11, use this range-based for-loop instead:

for (auto& iter : input_text)
{
    if (iter == isspace)
    {
        number_of_words++;
    }
}


-
As @r-s mentions, this just counts whitespace. Here's another solution from this answer:

unsigned int countWordsInString(std::string const& str)
{
    std::stringstream stream(str);
    return std::distance(std::istream_iterator(stream), std::istream_iterator());
}


I realize this may be difficult to understand. I'd still recommend holding onto the answer for future reference. If you want to try it out, include ` and `.

Code Snippets

std::size_t count_words(std::string const& input_text) {}
if (input_text.empty()) return 0;
for (auto iter = input_text.cbegin(); iter != input_text.cend(); ++iter)
{
    if (*iter == isspace)
    {
        number_of_words++;
    }
}
for (auto& iter : input_text)
{
    if (iter == isspace)
    {
        number_of_words++;
    }
}
unsigned int countWordsInString(std::string const& str)
{
    std::stringstream stream(str);
    return std::distance(std::istream_iterator<std::string>(stream), std::istream_iterator<std::string>());
}

Context

StackExchange Code Review Q#30547, answer score: 12

Revisions (0)

No revisions yet.