Day 81: Word Count of a String of 100DaysCodingChallenge

Hello all, 

#day81 

Day81 

Today's task was to Write a program to count all the words in a given string.
Words must be separated by only one space
Example:
Sample Input: hardik kotak
Sample Output: number of words : 2


I have started the 100 days of coding challenge to improve my programming skills..

Code : 

  //given input string.
    var OUT = 0;
    var IN = 1;
    // returns number of words in str
    function countWords( str)
    {
        var state = OUT;
        var wc = 0; // word count
        var i = 0;
        // Scan all characters one
        // by one
        while (i < str.length)
        {
            // If next character is a separator,
            // set the state as OUT
            if (str[i] == ' ' || str[i] == '\n'|| str[i] == '\t')
                state = OUT;
            // If next character is not a word
            // separator and state is OUT, then
            // set the state as IN and increment
            // word count
            else if (state == OUT)
            {
                state = IN;
                ++wc;
            }
            // Move to next character
            ++i;
        }
        return wc;
    }
    // Driver program to test above functions
        //var str = "One two     three\n four\tfive ";
var str = prompt("Enter a String : ")
console.log("No of words : " + countWords(str));

Output :     

 


Happy Coding:)

Thank you...      

Comments

Popular posts from this blog

Day 55: Pattern using loops of 100DaysCodingChallenge

Day 7: Square or Power Integer Numbers of 100DaysCodingChallenge

Day 45: Pattern using loops of 100DaysCodingChallenge