Program for word count in c

I need to write a function that will count words in a string. For the
purpose of this assignment, a «word» is defined to be a sequence
of non-null, non-whitespace characters, separated from other words by
whitespace.

This is what I have so far:

int words(const char sentence[ ]);

int i, length=0, count=0, last=0;
length= strlen(sentence);

for (i=0, i<length, i++)
 if (sentence[i] != ' ')
     if (last=0)
        count++;
     else
        last=1;
 else
     last=0;

return count;

I am not sure if it works or not because I can’t test it until my whole program is finished and I am not sure it will work, is there a better way of writing this function?

sehe's user avatar

sehe

368k47 gold badges449 silver badges622 bronze badges

asked Oct 2, 2012 at 21:44

PhillToronto's user avatar

3

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 http://ideone.com/uNgPL

#include <string.h>
#include <stdio.h>

int words(const char sentence[ ])
{
    int counted = 0; // result

    // state:
    const char* it = sentence;
    int inword = 0;

    do switch(*it) {
        case '': 
        case ' ': case 't': case 'n': case 'r': // TODO others?
            if (inword) { inword = 0; counted++; }
            break;
        default: inword = 1;
    } while(*it++);

    return counted;
}

int main(int argc, const char *argv[])
{
    printf("%dn", words(""));
    printf("%dn", words("t"));
    printf("%dn", words("   a      castle     "));
    printf("%dn", words("my world is a castle"));
}

answered Oct 2, 2012 at 22:11

sehe's user avatar

sehesehe

368k47 gold badges449 silver badges622 bronze badges

See the following example, you can follow the approach : count the whitespace between words .

int words(const char *sentence)
{
    int count=0,i,len;
    char lastC;
    len=strlen(sentence);
    if(len > 0)
    {
        lastC = sentence[0];
    }
    for(i=0; i<=len; i++)
    {
        if((sentence[i]==' ' || sentence[i]=='') && lastC != ' ')
        {
            count++;
        }
        lastC = sentence[i];
    }
    return count;
}

To test :

int main() 
{ 
    char str[30] = "a posse ad esse";
    printf("Words = %in", words(str));
}

Output :

Words = 4

Cini's user avatar

answered Oct 2, 2012 at 22:03

aleroot's user avatar

alerootaleroot

70.5k30 gold badges176 silver badges212 bronze badges

3

#include <ctype.h> // isspace()

int
nwords(const char *s) {
  if (!s) return -1;

  int n = 0;
  int inword = 0;
  for ( ; *s; ++s) {
    if (!isspace(*s)) {
      if (inword == 0) { // begin word
        inword = 1;
        ++n;
      }
    }
    else if (inword) { // end word
      inword = 0;
    }
  }
  return n;
}

answered Oct 2, 2012 at 22:21

jfs's user avatar

jfsjfs

394k191 gold badges973 silver badges1658 bronze badges

bool isWhiteSpace( char c )
{
    if( c == ' ' || c == 't' || c == 'n' )
        return true;
    return false;
}

int wordCount( char *string )
{
    char *s = string;
    bool inWord = false;
    int i = 0;

    while( *s )
    {
        if( isWhiteSpace(*s))
        {
            inWord = false;
            while( isWhiteSpace(*s) )
                s++;
        }
        else
        {
            if( !inWord )
            {
                inWord = true;
                i++;
            }
            s++;
        }
    }

    return i;
}

answered Mar 19, 2015 at 14:23

Andrew Bryant's user avatar

Here is one of the solutions. It counts words with multiple spaces or just space or space followed by the word.

#include <stdio.h>
int main()
{
    char str[80];
    int i, w = 0;
    printf("Enter a string: ");
    scanf("%[^n]",str);

    for (i = 0; str[i] != ''; i++)
    {
       
        if((str[i]!=' ' && str[i+1]==' ')||(str[i+1]=='' && str[i]!=' '))
        {
            w++;
        }
        
    }

    printf("The number of words = %d", w );

    return 0;
}

answered Jan 31, 2021 at 16:47

Venitta Raj R.'s user avatar

I know this is an old thread, but perhaps someone needs a simple solution, just checks for blank space in ascii and compares current char to that while also makign sure first char is not a space, cheers!

int count_words(string text){
int counter = 1;
int len = strlen(text);
for(int i = 0; i < len; i++){
    if(text[i] == 32 && i != 0) {
        counter++;
    }
}
return counter;}

answered Jun 27, 2022 at 10:42

Nlurins's user avatar

1

Here is another solution:

#include <string.h>

int words(const char *s)
{
    const char *sep = " tnrvf";
    int word = 0;
    size_t len;

    s += strspn(s, sep);

    while ((len = strcspn(s, sep)) > 0) {
        ++word;
        s += len;
        s += strspn(s, sep);
    }
    return word;
}

answered Oct 23, 2012 at 21:26

William Morris's user avatar

William MorrisWilliam Morris

3,5142 gold badges23 silver badges24 bronze badges

#include<stdio.h>

int main()   
{    
char str[50];    
int i, count=1;  
printf("Enter a string:n");    
gets(str);    
for (i=0; str[i]!=''; i++)   
        {
        if(str[i]==' ')    
                {
                count++;
                }
        }
printf("%in",count);    
}

RedBaron's user avatar

RedBaron

4,6975 gold badges41 silver badges65 bronze badges

answered Mar 18, 2014 at 10:16

Touseef Hashmi's user avatar

#include<stdio.h>
#include<string.h>

int getN(char *);


int main(){
    char str[999];
    printf("Enter Sentence: "); gets(str);
    printf("there are %d words", getN(str));
}


int getN(char *str){
    int i = 0, len, count= 0;
    len = strlen(str);
    if(str[i] >= 'A' && str[i] <= 'z')
       count ++;


    for (i = 1; i<len; i++)
        if((str[i]==' ' || str[i]=='t' || str[i]=='n')&& str[i+1] >= 'A' && str[i+1] <= 'z')
        count++;


return count;
}

answered Apr 18, 2015 at 0:55

sheehab's user avatar

0

#include <stdio.h>

int wordcount (char *string){

    int n = 0; 

    char *p = string ;
    int flag = 0 ;

    while(isspace(*p)) p++;


    while(*p){
        if(!isspace(*p)){
            if(flag == 0){
                flag = 1 ;
                n++;
            }
        }
        else flag = 0;
        p++;
    }

    return n ;
}


int main(int argc, char **argv){

    printf("%dn" , wordcount("    hello  worldnNo matter how many newline and spaces"));
    return 1 ;
}

leo.fcx's user avatar

leo.fcx

6,0592 gold badges21 silver badges37 bronze badges

answered Aug 4, 2015 at 15:46

Tite's user avatar

I found the posted question after finishing my function for a C class I’m taking. I saw some good ideas from code people have posted above. Here’s what I had come up with for an answer. It certainly is not as concise as other’s, but it does work. Maybe this will help someone in the future.

My function receives an array of chars in. I then set a pointer to the array to speed up the function if it was scaled up. Next I found the length of the string to loop over. I then use the length of the string as the max for the ‘for’ loop.
I then check the pointer which is looking at array[0] to see if it is a valid character or punctuation. If pointer is valid then increment to next array index. The word counter is incremented when the first two tests fail. The function then will increment over any number of spaces until the next valid char is found.
The function ends when null » or a new line ‘n’ character is found. Function will increment count one last time right before it exit to account for the word preceding null or newline. Function returns count to the calling function.

#include <ctype.h>

char wordCount(char array[]) {
    char *pointer;    //Declare pointer type char
    pointer = &array[0];  //Pointer to array

    int count; //Holder for word count
    count = 0; //Initialize to 0.

    long len;  //Holder for length of passed sentence
    len = strlen(array);  //Set len to length of string

    for (int i = 0; i < len; i++){

        //Is char punctuation?
        if (ispunct(*(pointer)) == 1) {
            pointer += 1;
            continue;
        }
        //Is the char a valid character?
        if (isalpha(*(pointer)) == 1) {
            pointer += 1;
            continue;
        }
        //Not a valid char.  Increment counter.
        count++;

        //Look out for those empty spaces. Don't count previous
        //word until hitting the end of the spaces.
        if (*(pointer) == ' ') {
            do {
                pointer += 1;
            } while (*(pointer) == ' ');
        }

        //Important, check for end of the string
        //or newline characters.
        if (*pointer == '' || *pointer == 'n') {
            count++;
            return(count);
        }
    }
    //Redundent return statement.
    count++;
    return(count);
}

answered Nov 7, 2017 at 20:09

pete's user avatar

petepete

791 silver badge3 bronze badges

I had this as an assignment…so i know this works.
The function gives you the number of words, average word length, number of lines and number of characters.
To count words, you have to use isspace() to check for whitespaces. if isspace is 0 you know you’re not reading whitespace. wordCounter is a just a way to keep track of consecutive letters. Once you get to a whitespace, you reset that counter and increment wordCount. My code below:

Use isspace(c) to

#include <stdio.h>
#include <ctype.h>

int main() {
  int lineCount = 0;
  double wordCount = 0;
  double avgWordLength = 0;
  int numLines = 0;
  int wordCounter = 0;
  double nonSpaceChars = 0;
  int numChars = 0;
  printf("Please enter text.  Use an empty line to stop.n"); 
  while (1) {
      int ic = getchar();
      if (ic < 0)    //EOF encountered
          break;
      char c = (char) ic;
      if (isspace(c) == 0 ){
      wordCounter++;
      nonSpaceChars++;
    }
      if (isspace(c) && wordCounter > 0){
      wordCount++;
      wordCounter =0;
    }
      if (c == 'n' && lineCount == 0) //Empty line
      { 
          break; 
      }
      numChars ++;
      if (c == 'n') {
          numLines ++;
          lineCount = 0;
      }
      else{
          lineCount ++;
    }
  }
  avgWordLength = nonSpaceChars/wordCount;
  printf("%fn", nonSpaceChars);
  printf("Your text has %d characters and %d lines.nYour text has %f words, with an average length of %3.2f ", numChars, numLines, wordCount, avgWordLength);
}

answered Jan 24, 2019 at 21:58

Peter Song's user avatar

Here is one solution. This one will count words correctly even if there are multiple spaces between words, no spaces around interpuncion symbols, etc. For example: I am,My mother is. Elephants ,fly away.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>


int countWords(char*);


int main() {
    char string[1000];
    int wordsNum;

    printf("Unesi nisku: ");
    gets(string);  /*dont use this function lightly*/

    wordsNum = countWords(string);

    printf("Broj reci: %dn", wordsNum);

    return EXIT_SUCCESS;
}


int countWords(char string[]) {
    int inWord = 0,
        n,
        i,
        nOfWords = 0;

    n = strlen(string);

    for (i = 0; i <= n; i++) {
        if (isalnum(string[i]))
            inWord = 1;
        else
            if (inWord) {
                inWord = 0;
                nOfWords++;
            }
    }

    return nOfWords;
}

answered Sep 2, 2013 at 20:57

Ivan's user avatar

1

this is a simpler function to calculate the number of words

int counter_words(char* a){`

 // go through chars in a
 // if ' ' new word
 int words=1;
 int i;
 for(i=0;i<strlen(a);++i)
 {
      if(a[i]==' ' && a[i+1] !=0)
      {
           ++words;
      }
 }

return words;}

answered Jul 8, 2016 at 9:14

marihan sherif 's user avatar

C program to count the total number of words in a string – In this article, we will detail in on the several means to count the total number of words in a string in C programming.

Suitable examples and sample programs have also been added so that you can understand the whole thing very clearly. The compiler has also been added with which you can execute it yourself.

The means used in this piece are as follows:

  • Using Standard Method
  • Using Function
  • Using Recursion
  • Using Pointers and While Loop

A string is nothing but an array of characters. The value of a string is determined by the terminating character. Its value is considered to be 0.

C Program Count Number Of Words In A String

As given in the image above, firstly, you need to enter a string.

The string specified here is as follows:

“always first never give up”

As you can see, there are 5 words in the given string.

It can be found out by basic reading itself.

Hence, doing the same in C programming is as follows:

Using Standard Method

  1. Read the entered string and initialize to s using gets(s).

2) We are finding the words count based on white spaces present in the given string. The ASCII value of white space is 32.

3) for loop iterates through the string with the structure for(i=0;s[i];i++),

If  ASCII value of any character of a string is equal to ASCII value of white space i.e 32, then increase the word count.

4) After all iterations of for loop increase the word count, if i>0.

5) Print the number of words present in the string.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

#include <stdio.h>

#include <string.h>

int main()

{

    char s[1000];  

    int i,words=0;

    printf(«Enter  the string : «);

    gets(s);

    for(i=0;s[i];i++)  

    {

     if(s[i]==32)

     words++;

}

if(i>0)

words++;

    printf(«no of words in string = %dn»,words);

    return 0;

}

Output:

Enter  the string: welcome to Cbeginners

no of words in string = 3

Using Function

  1. The main() function calls the stringwordcount(char *s) function, passing the string as an argument to the function.

2) The function stringwordcount() function compares each character’s ASCII value with white space ASCII value 32.If any character is equal to white space, then it increases the word count.

3) After all iterations of for loop, if i>0 then increase the word count by 1.

4) The function returns the word count to main() function. The main() function prints the number of words present in the given string.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

#include <stdio.h>

#include <string.h>

int stringwordcount(char *s)

{

    int i,words=0;

for(i=0;s[i];i++)  

    {

     if(s[i]==32)

     words++;

}

if(i>0)

      words++;

return words;

}

int main()

{

    char s[1000];  

    int wordscount;

    printf(«Enter  the string: «);

    gets(s);

    wordscount=stringwordcount(s);

    printf(«no of words in string = %dn»,wordscount);

}

Output:

Enter  the string: always first never give up

no of words in string = 5

Using Recursion

  1. The main() calls the function stringwordcount(char *s).

2) The function counts the number of words as

a) If the s[i] is null, then it increases the word count by 1 if i>0 and returns the word count value to the main() function.

b) If s[i] is not null, then compare ASCII value of s[i] with 32 which is the ASCII value of white space. If s[i] is equal to white space then increase the word count and call the function stringwordcount().

The function calls itself recursively until s[i] becomes to null.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

#include <stdio.h>

#include <string.h>

int stringwordcount(char *s)

{

    static int i,words=0;

    if(!s[i])

    {

       if(i>0)

      words++;

      return words;

}

else

{

     if(s[i++]==32)

     words++;

        stringwordcount(s);

}

}

int main()

{

    char s[1000];  

    int wordscount;

    printf(«Enter  the string: «);

    gets(s);

    wordscount=stringwordcount(s);

    printf(«no of words in string = %dn»,wordscount);

}

Output:

Enter  the string: Without music, life would be a mistake

no of words in string = 7

Using Pointers And While Loop
  1. The pointer variable p points the string s.

2) The while loop iterates until the character at the pointer variable become null.

a) If the ASCII value of the character at the pointer variable p is equal to white space ASCII value. Then increase the word count.

3) Increase the word count by 1 if the length of the string is greater than zero.

4) Print the number of words present in the string.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

#include <stdio.h>

#include <string.h>

int main()

{

    char s[1000],*p;  

    int words=0;

    printf(«Enter  the string : «);

    gets(s);

    p=s;

while(*p)  

    {

     if(*p++==32)

           words++;

}

    if(strlen(s)>0)

    words++;

    printf(«no of words in string = %dn»,words);

     return 0;

}

Output:

Enter the string: I have not failed. I‘ve just found 10,000 ways that won’t work

no of words in string = 12

Improve Article

Save Article

Like Article

  • Read
  • Discuss(120+)
  • Improve Article

    Save Article

    Like Article

    Given a string, count the number of words in it. The words are separated by the following characters: space (‘ ‘) or new line (‘n’) or tab (‘t’) or a combination of these.

    Method 1: The idea is to maintain two states: IN and OUT. The state OUT indicates that a separator is seen. State IN indicates that a word character is seen. We increment word count when previous state is OUT and next character is a word character. 

    C

    #include <bits/stdc++.h>

    using namespace std;

    #define OUT 0

    #define IN 1

    unsigned countWords(char *str)

    {

        int state = OUT;

        unsigned wc = 0;

        while (*str)

        {

            if (*str == ' ' || *str == 'n' || *str == 't')

                state = OUT;

            else if (state == OUT)

            {

                state = IN;

                ++wc;

            }

            ++str;

        }

        return wc;

    }

    int main(void)

    {

        char str[] = "One two     threen fourtfive ";

        cout<<"No of words : "<<countWords(str);

        return 0;

    }

    C

    #include <stdio.h>

    #define OUT    0

    #define IN    1

    unsigned countWords(char *str)

    {

        int state = OUT;

        unsigned wc = 0; 

        while (*str)

        {

            if (*str == ' ' || *str == 'n' || *str == 't')

                state = OUT;

            else if (state == OUT)

            {

                state = IN;

                ++wc;

            }

            ++str;

        }

        return wc;

    }

    int main(void)

    {

        char str[] = "One two         threen    fourtfive  ";

        printf("No of words : %u", countWords(str));

        return 0;

    }

    Java

    public class GFG {

        static final int OUT = 0;

        static final int IN = 1;

        static int countWords(String str)

        {

            int state = OUT;

            int wc = 0

            int i = 0;

            while (i < str.length())

            {

                if (str.charAt(i) == ' ' || str.charAt(i) == 'n'

                        || str.charAt(i) == 't')

                    state = OUT;

                else if (state == OUT)

                {

                    state = IN;

                    ++wc;

                }

                ++i;

            }

            return wc;

        }

        public static void main(String args[])

        {

            String str = "One two       threen fourtfive  ";

            System.out.println("No of words : " + countWords(str));

        }

    }

    Python3

    OUT = 0

    IN = 1

    def countWords(string):

        state = OUT

        wc = 0

        for i in range(len(string)):

            if (string[i] == ' ' or string[i] == 'n' or

                string[i] == 't'):

                state = OUT

            elif state == OUT:

                state = IN

                wc += 1

        return wc

    string = "One two         threen fourtfive "

    print("No. of words : " + str(countWords(string)))

    C#

    using System;

    class GFG {

        static int OUT = 0;

        static int IN = 1;

        static int countWords(String str)

        {

            int state = OUT;

            int wc = 0;

            int i = 0;

            while (i < str.Length)

            {

                if (str[i] == ' ' || str[i] == 'n'||

                                      str[i] == 't')

                    state = OUT;

                else if (state == OUT)

                {

                    state = IN;

                    ++wc;

                }

                ++i;

            }

            return wc;

        }

        public static void Main()

        {

            String str = "One two     threen fourtfive ";

            Console.WriteLine("No of words : "

                                  + countWords(str));

        }

    }

    PHP

    <?php

    $OUT = 0;

    $IN = 1;

    function countWords($str)

    {

        global $OUT, $IN;

        $state = $OUT;

        $wc = 0;

        $i = 0;

        while ($i < strlen($str))

        {

            if ($str[$i] == " " ||

                $str[$i] == "n" ||

                $str[$i] == "t")

                $state = $OUT;

            else if ($state == $OUT)

            {

                $state = $IN;

                ++$wc;

            }

            ++$i;

        }

        return $wc;

    }

    $str = "One two         threen fourtfive ";

    echo "No of words : " . countWords($str);

    ?>

    Javascript

    <script>

        var OUT = 0;

        var IN = 1;

        function countWords( str)

        {

            var state = OUT;

            var wc = 0;

            var i = 0;

            while (i < str.length)

            {

                if (str[i] == ' ' || str[i] == 'n'||

                                      str[i] == 't')

                    state = OUT;

                else if (state == OUT)

                {

                    state = IN;

                    ++wc;

                }

                ++i;

            }

            return wc;

        }

            var str = "One two     threen fourtfive ";

            document.write("No of words : "

                                  + countWords(str));

    </script>

    Time complexity: O(n)
    Auxiliary Space: O(1)

    This article is compiled by Aarti_Rathi and Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

    Method 2: using String.split() method

    1. Get the string to count the total number of words.
    2. Check if the string is empty or null then return 0.
    3. Use split() method of String class to split the string on whitespaces.
    4. The split() method breaks the given string around matches of the given regular expression and returns an array of string.
    5. The length of the array is the number of words in the given string.
    6. Now, print the result.

    Below is the implementation of the above approach:

    C++

    #include <bits/stdc++.h>

    using namespace std;

    int countWords(string str)

    {

      if (str.size() == 0) {

        return 0;

      }

      vector<string> words;

      string temp = "";

      for (int i = 0; i < str.size(); i++) {

        if (str[i] == ' ') {

          words.push_back(temp);

          temp = "";

        }

        else {

          temp += str[i];

        }

      }

      int count = 1;

      for (int i = 0; i < words.size(); i++) {

        if (words[i].size() != 0)

          count++;

      }

      return count;

    }

    int main()

    {

      string str = "One two       threen fourtfive ";

      cout << "No of words : " << countWords(str);

      return 0;

    }

    Java

    import java.io.*;

    class GFG

    {

        public static int

          countWords(String str)

        {

            if (str == null || str.isEmpty())

                return 0;

            String[] words = str.split("\s+");

            return words.length;

        }

        public static void main(String args[])

        {

            String str =

              "One two       threen fourtfive ";

            System.out.println("No of words : " +

               countWords(str));

        }

    }

    Python3

    def countWords(s):

        if s.strip() == "":

            return 0

        words = s.split()

        return len(words)

    if __name__ == "__main__":

        s = "One two       threen fourtfive "

        print("No of words : ", countWords(s))

    C#

    using System;

    public class GFG

    {

        public static int countWords(String str)

        {

            if (str == null || str.Length == 0)

            {

                return 0;

            }

            String[] words = str.Split(" ");

          int count = 1;

          for(int i=0;i<words.Length;i++){

              if(words[i].Length!=0) count++;

          }

            return count;

        }

        public static void Main(String[] args)

        {

            var str = "One two       threen fourtfive ";

            Console.WriteLine("No of words : " + GFG.countWords(str).ToString());

        }

    }

    Javascript

    function countWords(str)

    {

      if (str.length == 0) {

        return 0;

      }

      words = [];

      var temp = "";

      for (var i = 0; i < str.length; i++) {

        if (str[i] == " ") {

          words.push(temp);

          temp = "";

        }

        else {

          temp += str[i];

        }

      }

      var count = 1;

      for (var i = 0; i < words.length; i++) {

        if (words[i].length != 0)

          count++;

      }

      return count;

    }

      var str = "One two       threen fourtfive ";

      console.log("No of words : " +countWords(str));

    Time Complexity: O(N)
    Auxiliary Space: O(1)

    Method 3:  using StringTokenizer.countTokens() method

    1. Get the string to count the total number of words.
    2. Check if the string is empty or null then return 0.
    3. Create a StringTokenizer with the given string passed as a parameter.
    4. Count the total number of words in the given string using the countTokens() method.
    5. Now, print the result.

    Below is the implementation of the above approach:

    C++

    #include <bits/stdc++.h>

    using namespace std;

    int countWords(string s)

    {

        if (s.empty())

            return 0;

        istringstream is(s);

        int count = 0;

        string line;

        while (getline(is, line, '/'))

            ++count;

        return count;

    }

    int main()

    {

        string str = "One/ two /      three/n four/tfive ";

        cout << "No of words: " << countWords(str) << endl;

    }

    Java

    import java.util.StringTokenizer;

    class GFG

    {

        public static int

          countWords(String str)

        {

            if (str    == null || str.isEmpty())

                return 0;

            StringTokenizer tokens = new

              StringTokenizer(str);

            return tokens.countTokens();

        }

        public static void main(String args[])

        {

            String str =

              "One two       threen fourtfive ";

            System.out.println("No of words: " +

              countWords(str));

        }

    }

    Python3

    def count_words(s):

        if not s:

            return 0

        count = 0

        lines = s.split("/")

        for line in lines:

            if line.strip():

                count += 1

        return count

    s = "One/ two /      three/n four/tfive "

    print("No of words:", count_words(s))

    C#

    using System;

    class GFG

    {

      public static int

        countWords(String str)

      {

        if (string.IsNullOrEmpty(str))

          return 0;

        string[] tokens = str.Split(' ');

        return tokens.Length;

      }

      public static void Main()

      {

        string str =

          "One two     threen fourtfive ";

        Console.Write("No of words: " +

                      countWords(str));

      }

    }

    Javascript

    function countWords(s)

    {

      if (s.length === 0) return 0;

      const lines = s.split("/");

      return lines.length;

    }

    const str = "One/ two /      three/n four/tfive ";

    console.log(`No of words: ${countWords(str)}`);

    Time Complexity: O(N)
    Auxiliary Space : O(1)

    Method 4: using Character.isLetter() method

    1. Get the string to count the total number of words.
    2. Check if the string is empty or null then return 0.
    3. Converting the given string into a character array.
    4. Check if the character is a letter and index of the character array doesn’t equal to the end of the line that means, it is a word and set isWord by true.
    5. Check if the character is not a letter that means there is a space, then we increment the wordCount by one and set the isWord by false.
    6. Check for the last word of the sentence and increment the wordCount by one.
    7. Now, print the result.

    Below is the implementation of the above approach:

    C++

    #include <bits/stdc++.h>

    using namespace std;

    int countWords(char* str, int n)

    {

        if (n == 0) {

            return 0;

        }

        int wordCount = 0;

        bool isWord = false;

        int endOfLine = n - 1;

        for (int i = 0; i < n; i++) {

            if (isalpha(str[i]) && i != endOfLine) {

                isWord = true;

            }

            else if (!isalpha(str[i]) && isWord)

            {

                wordCount++;

                isWord = false;

            }

            else if (isalpha(str[i]) && i == endOfLine) {

                wordCount++;

            }

        }

        return wordCount;

    }

    int main()

    {

        char str[] = "One two     threen fourtfive ";

        int n = (sizeof(str) / sizeof(char)) - 1;

        cout << "No of words : " << countWords(str, n);

        return 0;

    }

    Java

    import java.io.*;

    class GFG

    {

        public static int

          countWords(String str)

        {

            if(str    == null || str.isEmpty())

                return 0;

            int wordCount = 0;

            boolean isWord = false;

            int endOfLine = str.length() - 1;

            char[] ch = str.toCharArray();

            for (int i = 0; i < ch.length; i++) {

                if (Character.isLetter(ch[i])

                    && i != endOfLine)

                    isWord = true;

                else if (!Character.isLetter(ch[i])

                         && isWord) {

                    wordCount++;

                    isWord = false;

                }

                else if (Character.isLetter(ch[i])

                         && i == endOfLine)

                    wordCount++;

            }

            return wordCount;

        }

        public static void main(String args[])

        {

            String str =

              "One two       threen fourtfive ";

            System.out.println("No of words : " +

              countWords(str));

        }

    }

    Python3

    def countWords(Str):

        if(Str == None or len(Str) == 0):

            return 0

        wordCount = 0

        isWord = False

        endOfLine = len(Str) - 1

        ch = list(Str)

        for i in range(len(ch)):

            if(ch[i].isalpha() and i != endOfLine):

                isWord = True

            elif(not ch[i].isalpha() and isWord):

                wordCount += 1

                isWord = False

            elif(ch[i].isalpha() and i == endOfLine):

                wordCount += 1

        return wordCount

    Str =  "One two       threen fourtfive "

    print("No of words :", countWords(Str))

    C#

    using System;

    public class GFG

    {

      static int countWords(String str)

      {

        if(str == null)

        {

          return 0;

        }

        int wordCount = 0;

        bool isWord = false;

        int endOfLine = str.Length - 1;

        char[] ch = str.ToCharArray();

        for (int i = 0; i < ch.Length; i++)

        {

          if (Char.IsLetter(ch[i]) 

              && i != endOfLine)

          {

            isWord = true;

          }

          else if (!Char.IsLetter(ch[i]) 

                   && isWord)

          {

            wordCount++;

            isWord = false;

          }

          else if (Char.IsLetter(ch[i])

                   && i == endOfLine)

          {

            wordCount++;

          }

        }

        return wordCount;

      }

      static public void Main ()

      {

        string str = "One two       threen fourtfive ";

        Console.WriteLine("No of words : " + countWords(str));

      }

    }

    Javascript

    <script>

    function countWords(str)

    {

            if(str    == null || str.length==0)

                return 0;

            let wordCount = 0;

            let isWord = false;

            let endOfLine = str.length - 1;

            let ch = str.split("");

            for (let i = 0; i < ch.length; i++) {

                if (isLetter(ch[i])

                    && i != endOfLine)

                    isWord = true;

                else if (!isLetter(ch[i])

                         && isWord) {

                    wordCount++;

                    isWord = false;

                }

                else if (isLetter(ch[i])

                         && i == endOfLine)

                    wordCount++;

            }

            return wordCount;

    }

    function isLetter(c) {

      return c.toLowerCase() != c.toUpperCase();

    }

    let str="One two       threen fourtfive ";

    document.write("No of words : " +

              countWords(str));

    </script>

    Time Complexity: O(N)
    Auxiliary Space: O(1) 

    Like Article

    Save Article

    C program: Count word,characters and space of a string

    C program: Count word, characters and space of a string

    In this article, we will discuss the concept of the C program: Count word, characters and space of a string

    In this post, we are going to learn how to count the total number of words, character and Space of the given string in C programming language

    C program: Count word,characters and space of a string

    Count words, characters and space

    C program: Count word, characters and space of a string

     Count words, character and Space using for loop

    The program allows the user to enter a String and then it counts and display the total number of words, character and Space of the given string using for loop in C programing language

    Program 1

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        char str[100];//declare and initialize char array
        int i;
        int words=1,characters=0,space=0;//display and initiolize variables
        printf("Please enter the string n");
        gets(str);//stored the string entered by user
    
        for(i=0; str[i] != ''; i++){
    
                if(str[i]!=' '){ // check characters
                    characters++;
                }
                 else if(str[i]==' ' || str[i] != 'n' || str[i] != 't'){ //check words
                    words++;
                }
        }
    printf("nTotal words: %d ",words); //display words
    printf("nTotal characters: %d",characters);//display characters
    printf("nSpace: %d ",(words-1));//display space
    getch();
        return 0;
    }
    

    When the above code is executed, it produces the following result

    Please enter the string
    This is C language
    
    Total words: 4
    Total characters: 15
    Space: 3

    Approach

    1. Declare a Character array as char str[100];
    2. Declare and initialize integer variables as words=1,space=0,caracters=0;
    3. The user asked to enter a string
    4. The given string is stored in the variable str;
    5. A for loop is used to count total characters of the given string.
    6. It is initialized as i=0, checks the condition whether str[i] != ‘’; and executes the loop until the given condition becomes true
    7. Use an if condition to test if(str[i]!=’ ‘), if it is true,  The characters becomes characters + 1( characters = characters +1);
    8. When it is false, control moves to the else-if part and evaluates the test-expression of else-if. if it is true The words becomes words+1(words=words+1);
    9. Finally, the program displays the total number of the words, characters and Space of the given string

    Count word, characters and space using while loop

    The program allows the user to enter a String and then it counts and display the total number of words, character and Space of the given string using while loop in C programing language

    Program 2

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        char str[100];
        int i;
        int words=1,characters=0,space=0;
        printf("Please enter the string n");
        gets(str); //store the given string
    
        i=0;
        while(str[i] != ''){
    
                if(str[i]!=' '){ // count characters
                    characters++;
                }
                 else if(str[i]==' ' || str[i] != 'n' || str[i] != 't'){
                    words++; // count words
                }
                i++;
        }
    printf("nTotal words: %d ",words);  //display total number of words
    printf("nTotal characters: %d",characters);  //display total number of characters
    printf("nSpace: %d ",(words-1));  //display total number of space
    getch();
        return 0;
    }
    

    When the above code is executed, it produces the following result

    Please enter the string
    code4coding.com C language tutorials
    
    Total words: 4
    Total characters: 33
    Space: 3

    Approach

    1. Declare a Character array as char str[100];
    2. Declare and initialize integer variables as words=1,space=0,caracters=0;
    3. The user asked to enter a string
    4. The given string is stored in the variable str;
    5. A while loop is used to count total characters of the given string.
    6. It is initialized as i=0, checks the condition whether str[i] != ‘’; and executes the loop until the given condition becomes true
    7. Use an if condition to test if(str[i]!=’ ‘), if it is true,  The characters becomes characters + 1( characters = characters +1);
    8. When it is false, control moves to the else-if part and evaluates the test-expression of else-if. if it is true The words becomes words+1(words=words+1);
    9. Finally, the program displays the total number of the words, characters and Space of the given string

    Count word, characters and space using do-while loop

    The program allows the user to enter a String and then it counts and display the total number of words, character and Space of the given string using do-while loop in C programing language

    Program 3

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        char str[100];
        int i;
        int words=1,characters=0,space=0;
        printf("Please enter the string n");
        gets(str); //count characters of a string wit out space
    
        i=0;
        do{
    
                if(str[i]!=' '){ // checl characters
                    characters++;
                }
                 else if(str[i]==' ' || str[i] != 'n' || str[i] != 't'){
                    words++; //check words
                }
                i++;
        }while(str[i] != '');
    printf("nTotal words: %d ",words); //display total number of words
    printf("nTotal characters: %d",characters); //display total number of characters
    printf("nSpace: %d ",(words-1)); //display total number of space
    getch();
        return 0;
    }
    

    When the above code is executed, it produces the following result

    Please enter the string
    Learn C basic tutorials code for coding
    
    Total words: 7
    Total characters: 33
    Space: 6

    Approach

    1. Declare a Character array as char str[100];
    2. Declare and initialize integer variables as words=1,space=0,caracters=0;
    3. The user asked to enter a string
    4. The given string is stored in the variable str;
    5. A do-while loop is used to count total characters of the given string.
    6. It is initialized as i=0, checks the condition whether str[i] != ‘’; and executes the loop until the given condition becomes true
    7. Use an if condition to test if(str[i]!=’ ‘), if it is true,  The characters becomes characters + 1( characters = characters +1);
    8. When it is false, control moves to the else-if part and evaluates the test-expression of else-if. if it is true The words becomes words+1(words=words+1);
    9. Finally, the program displays the total number of the words, characters and Space of the given string

    Suggested for you

    for loop in C language

    while loop in C language

    do-while loop in C  language

    Similar post

    Java program to count the total number of  upper case lower case numeric and special character

    C program to count the total number of  upper case lower case numeric and special character

    Python program to count the total number of  upper case lower case numeric and special character

    C++ program to count the total number of  upper case lower case numeric and special character

    Java program to count the total number of characters in the given string including space

    C program to count the total number of characters in the given string including space

    Python program to count the total number of characters in the given string including space

    Related posts:

    For our purpose, a word is a set of consecutive characters without any white-space. For example, ‘qnaplus‘ is a word but ‘qna plus‘ has two words. Here we’ll see how to write C program to count the number of words in a string.

    We can think of a simple solution of counting the white spaces in the string. Number of white spaces is equal to the number of words. But it will not work if you have multiple white spaces in between two words or if you have only white spaces, no word at all.

    We’ll figure out the algorithms that will work in all cases.

    The Program

    #include <stdio.h>
    
    #define MAX_LEN 1024
    
    int count_word(char *str) {
      int count = 0;
      int in_word = 0;
      int i = 0;
      do {
         if (str[i] == ' ' || str[i] == 't' || str[i] == '') {
           if(in_word) {
             in_word = 0;
             count++;
           }
         } else {
           in_word = 1;
         }
      } while(str[i++]);
    
      return count;
    }
    
    int main() {
      char str[1024];
      printf("Enter a string: ");
      gets(str);
    
      printf("Number of words in the above string is %d.n", count_word(str));
    }

    First we took input of a string and then passed the string to the count_word() function. The count_word() function returns the number of words in the input string.

    The Logic

    We traverse the whole string using a do-while loop. If we encounter a non-white-space character, we set the in_word flag to 1. But if we encounter a white-space character and the in_word flag is 1, we increment the word count. It suggests that a word ends with this white space. We set the in_word flag to 0 – we came out of the word.

    When we encounter a white-space and the in_word flag is 0, we don’t increment the word count because it suggests that the previous character is also a white-space.

    Note: Here we used do-while loop to process the last empty character (‘’) of the string.

    Here is the output.

    Another Logic

    We can tweak the above logic little bit to get the same effect. When we’ll encounter a white-space, we can check whether the previous character is also a white-space or not. If the previous character is not a white-space, then we are just at the end of a word. So we increment the word count in this case. We don’t need in_word flag. Here is the modified word_count() function.

    int count_word(char *str) {
      int count = 0;
      int i = 0;
      do {
         if (str[i] == ' ' || str[i] == 't' || str[i] == '') {
           if((i > 0) && (str[i-1] != ' ' && str[i-1] != 't' && str[i-1] != '')) {
             count++;
           }
         }
      } while(str[i++]);
    
      return count;
    }

    Using strtok()

    We can implement our logic using strtok() function. The strtok() function can split a string into tokens specified by a delimiter. We can count the token split by white-space delimiter.

    Here is our strtok() based implementation of word_count() function.

    int count_word(char *str) {
      int count = 0;
      char* token = strtok(str, " ");
      while (token != NULL) {
        count++;
        token = strtok(NULL, " ");
      }
    
      return count;
    }

    I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.
    View all posts by Srikanta

    If you also want to contribute, click here.

    In this article, we are going to learn How to count words in a text file in C.We will read each word from the text file in each iteration and increment a counter to count words.

    C fscanf function


    The scanf function is available in the C library. This function is used to read formatted input from a stream. The syntax of fscanf function is:

    Syntax

    int fscanf(FILE *stream, const char *format, …)

    Parameters

    • stream − This is the pointer to a FILE object that identifies the stream.
    • format − This is the C string that contains one or more of the following items − Whitespace character, Non-whitespace character, and Format specifiers. A format specifier will be as [=%[*][width][modifiers]type=].
    • How to Read text File word by word in C
    • How to Read File Line by Line in C
    • How to count words in a text file in C
    • How to get File Size timestamp access status in C
    • How to check if File Exists in C Language

    1. How to count words in a text file in C using fscanf


    In this c program, we are making use of the fscanf function to read the text file. The first thing we are going to do is open the file in reading mode. So using open() function and “r” read mode we opened the file.

    • The next step is to find the file stats like what is the size of the data this file contains. so we can allocate exact memory for the buffer that is going to hold the content of this file. We are using the stat() function to find the file size.
    • Once we have the size and buffer allocated for this size, we start reading the file by using the fscanf() function.
    • We keep reading the file word by word until we reach the end of file.In fscanf function, we are passing “%39[^-n] as the argument so we can read the text until we find the next word. The code will look like:
    fscanf(in_file, "%39[^-n]", file_contents)
    
    • We are maintaining a variable to count the number of words in the file. On each word count, we increment the counter.

    C Program to count words in a text file in C


    To run this program, we need one text file with the name Readme.txt in the same folder where we have our code.The content of the file is:

    Hello My name is 
    John 
    danny
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/stat.h>
    
    const char* filename = "Readme.txt";
    
    int main(int argc, char *argv[])
    {
    	int wordcount = 0;
        FILE *in_file = fopen(filename, "r");
        if (!in_file) 
    	{
            perror("fopen");
            return 0;
        }
    
        struct stat sb;
        if (stat(filename, &sb) == -1) 
    	{
            perror("stat");
            return 0;
        }
    
        char *file_contents = malloc(sb.st_size);
    
        while (fscanf(in_file, "%[^-n ] ", file_contents) != EOF) 
    	{
    		wordcount++;
            printf("%sn", file_contents);
        }
    	
    
    	printf("The file have total words = %dn",wordcount);
    	
        fclose(in_file);
        return 0;
    }
    

    Output

    Hello
    My
    name
    is
    John
    danny
    The file have total words = 6
    
    

    Понравилась статья? Поделить с друзьями:
  • Program for pdf to word
  • Project management with excel
  • Program fast for word
  • Project management templates in excel
  • Program equivalent to word