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 <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 three\n four\tfive ";
printf("No of words : %u", countWords(str));
return 0;
}
|
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 three\n four\tfive ";
cout<<"No of words : "<<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 three\n four\tfive ";
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 three\n four\tfive "
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 three\n four\tfive ";
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 three\n four\tfive ";
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 three\n four\tfive ";
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.
Method 2: using String.split() method
- Get the string to count the total number of words.
- Check if the string is empty or null then return 0.
- Use split() method of String class to split the string on whitespaces.
- The split() method breaks the given string around matches of the given regular expression and returns an array of string.
- The length of the array is the number of words in the given string.
- Now, print the result.
Below is the implementation of the above approach:
C
#include <stdio.h>
#include <string.h>
int countWords(char str[])
{
if (strlen(str) == 0) {
return 0;
}
char* token;
char* delim = " \n\t";
token = strtok(str, delim);
int count = 0;
while (token != NULL) {
count++;
token = strtok(NULL, delim);
}
return count;
}
int main()
{
char str[] = "One two three\n four\tfive ";
printf("No of words : %d", countWords(str));
return 0;
}
|
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 three\n four\tfive ";
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 three\n four\tfive ";
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 three\n four\tfive "
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 three\n four\tfive ";
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 three\n four\tfive ";
console.log("No of words : " +countWords(str));
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Method 3: using StringTokenizer.countTokens() method
- Get the string to count the total number of words.
- Check if the string is empty or null then return 0.
- Create a StringTokenizer with the given string passed as a parameter.
- Count the total number of words in the given string using the countTokens() method.
- Now, print the result.
Below is the implementation of the above approach:
C
#include <stdio.h>
#include <string.h>
int countWords(char* s)
{
if (s == NULL || strlen(s) == 0)
return 0;
int count = 0;
char* token = strtok(s, "/");
while (token != NULL) {
++count;
token = strtok(NULL, "/");
}
return count;
}
int main()
{
char str[] = "One/ two / three/n four/tfive ";
printf("No of words: %d\n", countWords(str));
return 0;
}
|
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 three\n four\tfive ";
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 three\n four\tfive ";
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
- Get the string to count the total number of words.
- Check if the string is empty or null then return 0.
- Converting the given string into a character array.
- 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.
- 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.
- Check for the last word of the sentence and increment the wordCount by one.
- Now, print the result.
Below is the implementation of the above approach:
C
#include <ctype.h>
#include <stdio.h>
int countWords(char* str, int n)
{
if (n == 0) {
return 0;
}
int wordCount = 0;
int isWord = 0;
int endOfLine = n - 1;
for (int i = 0; i < n; i++) {
if (isalpha(str[i]) && i != endOfLine) {
isWord = 1;
}
else if (!isalpha(str[i]) && isWord)
{
wordCount++;
isWord = 0;
}
else if (isalpha(str[i]) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}
int main()
{
char str[] = "One two three\n four\tfive ";
int n = (sizeof(str) / sizeof(char)) - 1;
printf("No of words : %d", countWords(str, n));
return 0;
}
|
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 three\n four\tfive ";
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 three\n four\tfive ";
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 three\n four\tfive "
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 three\n four\tfive ";
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 three\n four\tfive ";
document.write("No of words : " +
countWords(str));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
26 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...