Count number of words | Practice | GeeksforGeeks

Given a string consisting of spaces,\t,\n and lower case  alphabets.Your task is to count the number of words where spaces,\t and \n work as separators.
 
Example 1:
Input: S = "abc def"
Output: 2
Explanation: There is a space at 4th
position which works as a seperator
between "abc" and "def"

 
Example 2:
Input: S = "a\nyo\n"
Output: 2
Explanation: There are two words "a"
and "yo" which are seperated by "\n".

Your Task:  
You don't need to read input or print anything. Your task is to complete the function countWords() which accepts a string as input and returns number of words present in it.

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
where N is length of given String.

Constraints:
2 <= Length of String <= 106
 
+1
mayank20212 weeks ago
C++ : 0.06/1.5int countWords(string s){   int count=0, flag=0;         for(int i=0; i<s.size(); i++)    {        if( (s[i]==' ' || s[i]=='\\' )  )         {             if(s[i]=='\\' && (s[i+1]=='t' || s[i+1]=='n') ) i++;             if(flag) count++;              flag=0;         }        else         {         flag=1;         }            }    if (flag) count++;        return count;   }
0
premranjan88046
This comment was deleted.
0
triple2double18 months ago
int countWords(string s){   int count = 0;   int n = s.length();   int seenletter =false;   int i=0;   while(i<n)   {       seenletter =false;       while (i<n&&isalpha(s[i]))           {               seenletter=true;               i++;           }            if(s[i]=='\\')           i+=2;      else           i++;         if(seenletter==true)           count++;   }   return count;}
 
0
martial8 months ago
martial
what is isalpha?
0
shahzdor9 months ago
shahzdor
Python solution showing error
class Solution:  def countWords(self, s):    count=0    strx=0    for i in s:      if i==' ' or i=='\n' or i=='\t' and strx>0:        count+=1        strx=0      else:        strx+=1    if strx>0:      count+=1    return count
###################
from re import split
class Solution:  def countWords(self, s):    words = s.split()    return len(words)
Both are giving error
0
ANAS MALVAT9 months ago
ANAS MALVAT
for(int i = 0 ; i < s.length() ; i ++)    {        if(isalpha(s[i]))        {            if(!flag)            {                flag = 1;                ret++;            }        }        else  if(s[i] ==' ')        {            flag = 0;        }        else if(!isalpha(s[i]) and s[i + 1] == 'n')        {            i++;            flag = 0;        }        else if(!isalpha(s[i]) and s[i + 1] =='t')        {            i++;            flag = 0;        }    }    return ret;
0
dhanraj kalantri10 months ago
dhanraj kalantri
int countWords(string s){int count = 0, i;string x = "";for (i = 0; i < s.length(); i++){if (isalpha(s[i])){x += s[i];continue;}else if (s[i] == ' '){if (x != ""){count++;x = "";}}else{if (x != ""){count++;x = "";}i++;}}if (x != "")count++;return count;}
0
Debojyoti Sinha10 months ago
Debojyoti Sinha
Total Time Taken: 0.1/1.4 ✅
int countWords(string s){    int res = 0;        for(int i = 0; i < s.size(); i++)    {        if(isalpha(s[i]))        {            res++;        }                while(i < s.size() and isalpha(s[i]))        {            i++;        }                if(i < s.size() and s[i] == '\\')        {            i++;        }    }        return res;}
0
Bharat Gupta1 year ago
Bharat Gupta
Refer to the hint if getting an error while comparing '\'.
int countWords(string s){    int words = 0, len = s.length();    for(int i = 0; i < len; i++){           if(isalpha(s[i])) words++;                while(i < len and isalpha(s[i])) i++;                if(s[i] == '\\') i++;    }        return words;}
-4
Babita Kumari1 year ago
Babita Kumari
int countWords(string str){
    int wc = 1;
   for(int i=0;str[i]!='\0';i++)     {
        if (str[i] == '\n' || str[i] == ' ' || str[i] == '\t')             wc+=1;    }
    return wc;     //code here
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.