C++ function to count all the words in a string

count number of words in a string in c
count number of words in a string - c++
c program to count number of repeated words in a string
word count program in c for a file
c program to count number of words in a string using pointers
program to count number of words in a string in java
java program to count number of repeated words in a string
program to count length of each word in a string in c

I was asked this during an interview and apparently it's an easy question but it wasn't and still isn't obvious to me.

Given a string, count all the words in it. Doesn't matter if they are repeated. Just the total count like in a text files word count. Words are anything separated by a space and punctuation doesn't matter, as long as it's part of a word.

For example: A very, very, very, very, very big dog ate my homework!!!! ==> 11 words

My "algorithm" just goes through looking for spaces and incrementing a counter until I hit a null. Since i didn't get the job and was asked to leave after that I guess My solution wasn't good? Anyone have a more clever solution? Am I missing something?

A less clever, more obvious-to-all-of-the-programmers-on-your-team method of doing it.

#include <cctype>

int CountWords(const char* str)
{
   if (str == NULL)
      return error_condition;  // let the requirements define this...

   bool inSpaces = true;
   int numWords = 0;

   while (*str != '\0')
   {
      if (std::isspace(*str))
      {
         inSpaces = true;
      }
      else if (inSpaces)
      {
         numWords++;
         inSpaces = false;
      }

      ++str;
   }

   return numWords;
}

Count words in a given string, word count. // Scan all characters one by one C program to count no of words from given input string. */ Driver program to tes above functions. int main(  C Program to Count Total Number of Words in a String Example 1 This program allows the user to enter a string (or character array), and a character value. Next, it will count the total number of words present inside this string using For Loop .

Assuming words are white space separated:

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>());
}

Note: There may be more than one space between words. Also this does not catch other white space characters like tab new line or carriage return. So counting spaces is not enough.

The stream input operator >> when used to read a string from a stream. Reads one white space separated word. So they were probably looking for you to use this to identify words.

std::stringstream  stream(str);
std::string        oneWord;

stream >> oneWord; // Reads one space separated word.

When can use this to count words in a string.

std::stringstream  stream(str);
std::string        oneWord;
unsigned int       count = 0;

while(stream >> oneWord) { ++count;}
// count now has the number of words in the string.

Getting complicated: Streams can be treated just like any other container and there are iterators to loop through them std::istream_iterator. When you use the ++ operator on an istream_iterator it just read the next value from the stream using the operator >>. In this case we are reading std::string so it reads a space separated word.

std::stringstream  stream(str);
std::string        oneWord;
unsigned int       count = 0;

std::istream_iterator loop = std::istream_iterator<std::string>(stream);
std::istream_iterator end  = std::istream_iterator<std::string>();

for(;loop != end; ++count, ++loop) { *loop; }

Using std::distance just wraps all the above in a tidy package as it find the distance between two iterators by doing ++ on the first until we reach the second.

To avoid copying the string we can be sneaky:

unsigned int countWordsInString(std::string const& str)
{
    std::stringstream stream;

    // sneaky way to use the string as the buffer to avoid copy.
    stream.rdbuf()->pubsetbuf (str.c_str(), str.length() );
    return std::distance(std::istream_iterator<std::string>(stream), std::istream_iterator<std::string>());
}

Note: we still copy each word out of the original into a temporary. But the cost of that is minimal.

C exercises: Count the total number of words in a string, C programming, exercises, solution: Write a program in C to count the total number of words in a string. How to count occurrences of a word in a string (LINQ) (C#) 07/20/2015; 2 minutes to read +5; In this article. This example shows how to use a LINQ query to count the occurrences of a specified word in a string. Note that to perform the count, first the Split method is called to create an array of words.

Another boost based solution that may work (untested):

vector<string> result;
split(result, "aaaa bbbb cccc", is_any_of(" \t\n\v\f\r"), token_compress_on);

More information can be found in the Boost String Algorithms Library

C Program to Count Total Number of Words in a String, C Program to Count Total Number of Words in a String. OUTPUT. ANALYSIS. Here, we used For Loop to iterate each and every character in a String, and find the empty spaces in it. First For Loop – First Iteration: for(i = 0; str[i] != '\0' ; i++) The condition is True. if(str[i] == ' ' || str[i] == '\n' || str[i] == '\t') Basic C programming, If else, For loop, String. Logic to count number of words in a string. To count total number of words in a string we just need to count total number of white spaces. White space characters includes single blank space ' ', Tab \t, New line .

You can use the std::count or std::count_if to do that. Below a simple example with std::count:

//Count the number of words on string
#include <iostream>
#include <string>
#include <algorithm> //count and count_if is declared here

int main () {
    std::string sTEST("Text to verify how many words it has.");

    std::cout << std::count(sTEST.cbegin(), sTEST.cend(), ' ')+1;

    return 0;
}

UPDATE: Due the observation made by Aydin Özcan (Nov 16) I made a change to this solution. Now the words may have more than one space between them. :)

//Count the number of words on string
#include <string>
#include <iostream>

int main () {
    std::string T("Text to   verify :  How many words does it   have?");

    size_t NWords = T.empty() || T.back() == ' ' ? 0 : 1;
    for (size_t s = T.size(); s > 0; --s)
        if (T[s] == ' ' && T[s-1] != ' ') ++NWords;

    std::cout << NWords;

    return 0;
}

Counting words in a string - c programming, You needed int words(const char sentence[]) { }. (note braces). For loops go with ; instead of , . Without any disclaimer, here's what I'd have written: See it live  Here is the output: Enter a string: Testing this out. A: Count vowels B: Count non-vowels C: Display string length D: Display string in reverse E: Display string in uppercase F: Display string in lowercase G: Count words in string H: Enter another string I: Exit Enter your choice g There are 2 words in this string.

This can be done without manually looking at every character or copying the string.

#include <boost/iterator/transform_iterator.hpp>
#include <cctype>

boost::transform_iterator
    < int (*)(int), std::string::const_iterator, bool const& >
    pen( str.begin(), std::isalnum ), end( str.end(), std::isalnum );

size_t word_cnt = 0;

while ( pen != end ) {
    word_cnt += * pen;
    pen = std::mismatch( pen+1, end, pen ).first;
}

return word_cnt;

I took the liberty of using isalnum instead of isspace.

This is not something I would do at a job interview. (It's not like it compiled the first time.)

Or, for all the Boost haters ;v)

if ( str.empty() ) return 0;

size_t word_cnt = std::isalnum( * str.begin() );

for ( std::string::const_iterator pen = str.begin(); ++ pen != str.end(); ) {
    word_cnt += std::isalnum( pen[ 0 ] ) && ! std::isalnum( pen[ -1 ] );
}

return word_cnt;

C Program Count Number Of Words In A String, C program to count the total number of words in a string – In this article, we will detail in on the 4) After all iterations of for loop increase the word count, if i>0. To understand how this works, recall that after conversion tolower each letter has a code between a and z, and that the codes are consecutive. As the result, tolower (*p) - 'a' evaluates to a number from 0 to 25, inclusive, representing the letter's sequential number in the alphabet. This code combines ++ and *p to shorten the program.

Count the number of words in a given string using C, C a program to count the number of words in a given string. Two words are separated by one or more blank spaces. C Program #include #include void main(​)  String.Split is handy, but it unnecessarily generates a (potentially) large number of String objects, which in turn creates an unnecessary burden on the garbage collector. For each word in your text, a new String object needs to be instantiated, and then soon collected since you are not using it.

C program to count number of words in a string, How to find total number of words in a given string using loops in C programming. Logic to count total number of words in a string. Example. C String function – strcmp It compares the two strings and returns an integer value. If both the strings are same (equal) then this function would return 0 otherwise it may return a negative or positive value based on the comparison. If string1 < string2 OR string1 is a substring of string2 then it would result in a negative value.

C program to count occurrences of a word in a string, How to count total occurrences of a given word in a string using loop in C Must know - Program to search all occurrences of a word in given string <string.h> #​define MAX_SIZE 100 // Maximum string size /* Function  Count the number of words in a given string using C Levels of difficulty: Basic / perform operation: String C a program to count the number of words in a given string.

Comments
  • "until I hit a null" - how are nulls special in a string in C++?
  • @Cubbi: Well spotted. I did not join the dots there.
  • By the answers given below, it seems that more context is really required. Some industries use "modern" C++, finding that the cost of using STL and boost more than makes up for the productivity gains. Other industries prefer to use a more C-like version of C++ so that there's a more direct mapping of code lines to processor instructions. Future answers to questions along these lines would be well served to determine at least the industry the candidate is applying to.
  • You have as much context as I do. The interviewer was not very cooperative and didn't give much feedback when I asked if he was looking for something clever or just brute force. While Martin gave a bad ass answer below and fantastic description, I really got the feeling from the interviewer that it was just a test to see if I could code something "basic". But then again I didn't get the offer so what do I know...
  • Its relatively standard to use the stream operator >> to get words. I don't see how this is more obvious as it takes a while to read all this code and understand it.
  • @dash-tom-bang: My bad. I don't see why immediately why it works but testing it on codepad seems to work. I think it's unintuitive though.
  • @dash-tom-bang: I deleted my answer because I found some cases where it gives wrong answers. That said, I still think the design was more intuitive than this one.
  • It may be standard to use >> to get words, but for those of us who never deal with text files the standard is irrelevant. The point of my opening statement is that this code requires only that the user understands very basic parts of the language.
  • This is the answer I'd like to see as an interviewer. When asking someone to implement a trivial algorithm in an interview, the interviewer is usually trying to see if the person can write a piece of low-level code sanely without introducing unnecessary overhead, complexity, or obfuscation. They are not attempting to engage in a dick-measuring contest over obscure library features or challenge the interviewee to a game of code golf.
  • Easy to read for whom? The author or the unknown maintainer? (It could be that a place of employ demands that folks know the C++ standard library, but I have yet to be employed by such a facility. :) ) (Note that I think this is a neat solution, but have been so far away from proper C++ for so long that it'd take me by surprise to run across it.)