Count words in a given string
Last Updated :
17 Apr, 2024
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 <iostream>
#include <cstring>
using namespace std;
#define OUT 0
#define IN 1
// Function to count the number of words in a string
int countWords(char* str, int n) {
if (n == 0) {
return 0;
}
int wordCount = 0;
int state = OUT; // Initial state is OUT
// Traverse all characters of the input string
for (int i = 0; i < n; i++) {
// Check for backslash first
if (str[i] == '\\') {
i++; // Skip next character (after backslash)
continue;
}
// If the current character is a word character
if (isalnum(str[i])) {
// If previous state was OUT, increment word count and change state to IN
if (state == OUT) {
wordCount++;
state = IN;
}
}
// If the current character is not a word character
else {
// Change state to OUT
state = OUT;
}
}
return wordCount;
}
// Driver code
int main() {
char str[] ="abc\\p\""; // Input string
cout << "No of words: " << countWords(str, strlen(str)) << endl; // Count words
return 0;
}
// This code is contributed by kislay__kumar
C
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define OUT 0
#define IN 1
// Function to count the number of words in a string
int countWords(char* str, int n) {
if (n == 0) {
return 0;
}
int wordCount = 0;
int state = OUT; // Initial state is OUT
// Traverse all characters of the input string
for (int i = 0; i < n; i++) {
// Check for backslash first
if (str[i] == '\\') {
i++; // Skip next character (after backslash)
continue;
}
// If the current character is a word character
if (isalnum(str[i])) {
// If previous state was OUT, increment word count and change state to IN
if (state == OUT) {
wordCount++;
state = IN;
}
}
// If the current character is not a word character
else {
// Change state to OUT
state = OUT;
}
}
return wordCount;
}
// Driver code
int main() {
char str[] ="abc\\p\""; // Input string
printf("No of words: %d\n", countWords(str, strlen(str))); // Count words
return 0;
}
// This code is contributed by kislay__kumar
Java
public class WordCount {
// Function to count the number of words in a string
public static int countWords(String str) {
if (str.length() == 0) {
return 0;
}
int wordCount = 0;
int state = 0; // Initial state is OUT
// Traverse all characters of the input string
for (int i = 0; i < str.length(); i++) {
// Check for backslash first
if (str.charAt(i) == '\\') {
i++; // Skip next character (after backslash)
continue;
}
// If the current character is a word character
if (Character.isLetterOrDigit(str.charAt(i))) {
// If previous state was OUT, increment word count and change state to IN
if (state == 0) {
wordCount++;
state = 1;
}
}
// If the current character is not a word character
else {
// Change state to OUT
state = 0;
}
}
return wordCount;
}
// Driver code
public static void main(String[] args) {
String str = "abc\\p\""; // Input string
System.out.println("No of words: " + countWords(str)); // Count words
}
}
// This code is contributed by kislay__kumar
Python3
import re
# Function to count the number of words in a string
def count_words(string):
word_count = 0
state = 0 # Initial state is OUT
# Traverse all characters of the input string
for char in re.findall(r"\\.|[\w]", string):
# Check for backslash first
if char == '\\':
continue
# If the current character is a word character
if char.isalnum():
# If previous state was OUT, increment word count and change state to IN
if state == 0:
word_count += 1
state = 1
# If the current character is not a word character
else:
# Change state to OUT
state = 0
return word_count
# Driver code
string = "abc\\p\"" # Input string
print("No of words:", count_words(string)) # Count words
"""This code is contributed by kislay__kumar"""
C#
using System;
class Program
{
// Function to count the number of words in a string
static int CountWords(string str)
{
if (str.Length == 0)
{
return 0;
}
int wordCount = 0;
int state = 0; // Initial state is OUT
// Traverse all characters of the input string
foreach (char c in str)
{
// Check for backslash first
if (c == '\\')
{
continue;
}
// If the current character is a word character
if (char.IsLetterOrDigit(c))
{
// If previous state was OUT, increment word count and change state to IN
if (state == 0)
{
wordCount++;
state = 1;
}
}
// If the current character is not a word character
else
{
// Change state to OUT
state = 0;
}
}
return wordCount;
}
// Driver code
static void Main()
{
string str = "abc\\p\""; // Input string
Console.WriteLine("No of words: " + CountWords(str)); // Count words
}
}
// This code is contributed by kislay__kumar
Javascript
// Function to count the number of words in a string
function countWords(str) {
if (str.length === 0) {
return 0;
}
let wordCount = 0;
let state = 0; // Initial state is OUT
// Traverse all characters of the input string
for (let i = 0; i < str.length; i++) {
// Check for backslash first
if (str[i] === '\\') {
i++; // Skip next character (after backslash)
continue;
}
// If the current character is a word character
if (str[i].match(/[a-zA-Z0-9]/)) {
// If previous state was OUT, increment word count and change state to IN
if (state === 0) {
wordCount++;
state = 1;
}
}
// If the current character is not a word character
else {
// Change state to OUT
state = 0;
}
}
return wordCount;
}
// Driver code
let str = "abc\\p\""; // Input string
console.log("No of words: " + countWords(str)); // Count words
// This code is contributed by kislay__kumar
PHP
<?php
// Function to count the number of words in a string
function countWords($str) {
if (strlen($str) === 0) {
return 0;
}
$wordCount = 0;
$state = 0; // Initial state is OUT
// Traverse all characters of the input string
for ($i = 0; $i < strlen($str); $i++) {
// Check for backslash first
if ($str[$i] === '\\') {
$i++; // Skip next character (after backslash)
continue;
}
// If the current character is a word character
if (ctype_alnum($str[$i])) {
// If previous state was OUT, increment word count and change state to IN
if ($state ===
// This code is contributed by kislay__kumar
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++
// C++ program to count total
// number of words in the string
#include <bits/stdc++.h>
using namespace std;
// Function to count total number
// of words in the string
int countWords(string str)
{
// Check if the string is null
// or empty then return zero
if (str.size() == 0) {
return 0;
}
// Splitting the string around
// matches of the given regular
// expression
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 number of words
// in the given string
return count;
}
int main()
{
// Given String str
string str = "abc\\p\"";
// Print the result
cout << "No of words : " << countWords(str);
return 0;
}
// This code is contributed by kislay__kumar
C
// C program to count total
// number of words in the string
#include <stdio.h>
#include <string.h>
// Function to count total number
// of words in the string
int countWords(char str[])
{
// Check if the string is null
// or empty then return zero
if (strlen(str) == 0) {
return 0;
}
// Splitting the string around
// matches of the given regular
// expression
char* token;
char* delim = " \n\t";
token = strtok(str, delim);
int count = 0;
while (token != NULL) {
count++;
token = strtok(NULL, delim);
}
// Return number of words
// in the given string
return count;
}
int main()
{
// Given String str
char str[] = "abc\\p\"";
// Print the result
printf("No of words : %d", countWords(str));
return 0;
}
// This code is contributed by kislay__kumar
Java
// Java program to count total
// number of words in the string
import java.io.*;
class GFG
{
// Function to count total number
// of words in the string
public static int
countWords(String str)
{
// Check if the string is null
// or empty then return zero
if (str == null || str.isEmpty())
return 0;
// Splitting the string around
// matches of the given regular
// expression
String[] words = str.split("\\s+");
// Return number of words
// in the given string
return words.length;
}
// Driver Code
public static void main(String args[])
{
// Given String str
String str = "abc\\p\"";
// Print the result
System.out.println("No of words : " +
countWords(str));
}
}
// This code is contributed by kislay__kumar
Python3
# Python program to count total
# number of words in the string
def countWords(s):
# Check if the string is null
# or empty then return zero
if s.strip() == "":
return 0
# Splitting the string
words = s.split()
return len(words)
if __name__ == "__main__":
s = "abc\\p\""
print("No of words : ", countWords(s))
"""This code is contributed by kislay__kumar"""
C#
// Include namespace system
using System;
// C# program to count total
// number of words in the string
public class GFG
{
// Function to count total number
// of words in the string
public static int countWords(String str)
{
// Check if the string is null
// or empty then return zero
if (str == null || str.Length == 0)
{
return 0;
}
// Splitting the string around
// matches of the given regular
// expression
String[] words = str.Split(" ");
int count = 1;
for(int i=0;i<words.Length;i++){
if(words[i].Length!=0) count++;
}
// Return number of words
// in the given string
return count;
}
// Driver Code
public static void Main(String[] args)
{
// Given String str
var str = "abc\\p\"";
// Print the result
Console.WriteLine("No of words : " + GFG.countWords(str).ToString());
}
}
// This code is contributed by kislay__kumar
Javascript
// Javascript program to count total
// number of words in the string
// Function to count total number
// of words in the string
function countWords(str)
{
// Check if the string is null
// or empty then return zero
if (str.length == 0) {
return 0;
}
// Splitting the string around
// matches of the given regular
// expression
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 number of words
// in the given string
return count;
}
// Driver code
// Given String str
var str = "abc\\p\"";
// Print the result
console.log("No of words : " +countWords(str));
// This code is contributed by kislay__kumar
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++
// C++ program to count total
// number of words in the string
#include <bits/stdc++.h>
using namespace std;
// Function to count total number
// of words in the string
int countWords(string s)
{
// Check if the string is null
// or empty then return zero
if (s.empty())
return 0;
istringstream is(s);
int count = 0;
string line;
while (getline(is, line, '/'))
++count;
return count;
}
int main()
{
string str = "abc\\p\"";
// Print the result
cout << "No of words: " << countWords(str) << endl;
}
// This code is contributed by kislay__kumar
C
// C program to count total
// number of words in the string
#include <stdio.h>
#include <string.h>
// Function to count total number
// of words in the string
int countWords(char* s)
{
// Check if the string is null
// or empty then return zero
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[] = "abc\\p\"";
// Print the result
printf("No of words: %d\n", countWords(str));
return 0;
}
// This code is contributed by kislay__kumar
Java
// Java program to count total
// number of words in the string
import java.util.StringTokenizer;
class GFG
{
// Function to count total number
// of words in the string
public static int
countWords(String str)
{
// Check if the string is null
// or empty then return zero
if (str == null || str.isEmpty())
return 0;
// Create a StringTokenizer with the
// given string passed as a parameter
StringTokenizer tokens = new
StringTokenizer(str);
// Return the number of words
// in the given string using
// countTokens() method
return tokens.countTokens();
}
// Driver Code
public static void main(String args[])
{
// Given String str
String str = "abc\\p\"";
// Print the result
System.out.println("No of words: " +
countWords(str));
}
}
// This code is contributed by kislay__kumar
Python3
def count_words(s):
# Check if the string is null or empty then return zero
if not s:
return 0
count = 0
lines = s.split("/")
for line in lines:
# Ignore empty lines
if line.strip():
count += 1
return count
s = "abc\\p\""
print("No of words:", count_words(s))
# This code is contributed by kislay__kumar
C#
// C# program to count total
// number of words in the string
using System;
class GFG
{
// Function to count total number
// of words in the string
public static int
countWords(String str)
{
// Check if the string is null
// or empty then return zero
if (string.IsNullOrEmpty(str))
return 0;
// Create a String Token with the
// given string passed as a parameter
string[] tokens = str.Split(' ');
// Return the number of words
// in the given string using
// Length method
return tokens.Length;
}
// Driver Code
public static void Main()
{
// Given String str
string str = "abc\\p\"";
// Print the result
Console.Write("No of words: " +
countWords(str));
}
}
// This code is contributed by kislay__kumar
Javascript
// JavaScript program to count total
// number of words in the string
// Function to count total number
// of words in the string
function countWords(s)
{
// Check if the string is null
// or empty then return zero
if (s.length === 0) return 0;
const lines = s.split("/");
return lines.length;
}
const str = "abc\\p\"";
// Print the result
console.log(`No of words: ${countWords(str)}`);
// This code is contributed by kislay__kumar
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 <iostream>
#include <ctype.h> // For isalpha()
using namespace std;
// Function to count total number of words in the string
int countWords(char* str) {
int wordCount = 0;
bool isWord = false;
// Iterate through the string until null terminator (\0)
for (int i = 0; str[i] != '\0'; i++) {
// Check if the character is a letter or escaped backslash and set isWord to true
if (isalpha(str[i]) || (str[i] == '\\' && str[i + 1] != '\0')) { // Handle escaped backslash
isWord = true;
// Skip the escaped character if it's a backslash
if (str[i] == '\\') {
i++;
}
}
// Increment wordCount if a word ends (space or null terminator)
else if (!isalpha(str[i]) && !isdigit(str[i]) && isWord) { // Exclude digits for literal interpretation
wordCount++;
isWord = false;
}
}
// Handle the last word (if it ends with a letter)
if (isWord) {
wordCount++;
}
return wordCount;
}
int main() {
char str[] = "abc\\p\"";
cout << "No of words : " << countWords(str) << endl;
return 0;
}
// This code is contributed by kislay__kumar
C
#include <stdio.h>
#include <ctype.h> // For isalpha()
// Function to count total number of words in the string
int countWords(char* str) {
int wordCount = 0;
int isWord = 0; // false
// Iterate through the string until null terminator (\0)
for (int i = 0; str[i] != '\0'; i++) {
// Check if the character is a letter or escaped backslash and set isWord to true
if (isalpha(str[i]) || (str[i] == '\\' && str[i + 1] != '\0')) { // Handle escaped backslash
isWord = 1; // true
// Skip the escaped character if it's a backslash
if (str[i] == '\\') {
i++;
}
}
// Increment wordCount if a word ends (space or null terminator)
else if (!isalpha(str[i]) && !isdigit(str[i]) && isWord) { // Exclude digits for literal interpretation
wordCount++;
isWord = 0; // false
}
}
// Handle the last word (if it ends with a letter)
if (isWord) {
wordCount++;
}
return wordCount;
}
int main() {
char str[] = "abc\\p\"";
printf("No of words : %d\n", countWords(str));
return 0;
}
// This code is contributed by kislay__kumar
Java
public class Main {
// Function to count total number of words in the string
static int countWords(String str) {
int wordCount = 0;
boolean isWord = false;
// Iterate through the string
for (int i = 0; i < str.length(); i++) {
// Check if the character is a letter or escaped backslash and set isWord to true
if (Character.isLetter(str.charAt(i)) || (str.charAt(i) == '\\' && i + 1 < str.length())) { // Handle escaped backslash
isWord = true;
// Skip the escaped character if it's a backslash
if (str.charAt(i) == '\\') {
i++;
}
}
// Increment wordCount if a word ends (space or end of string)
else if (!Character.isLetter(str.charAt(i)) && !Character.isDigit(str.charAt(i)) && isWord) { // Exclude digits for literal interpretation
wordCount++;
isWord = false;
}
}
// Handle the last word (if it ends with a letter)
if (isWord) {
wordCount++;
}
return wordCount;
}
public static void main(String[] args) {
String str = "abc\\p\"";
System.out.println("No of words : " + countWords(str));
}
}
// This code is contributed by kislay__kumar
Python3
import re
# Function to count total number of words in the string
def count_words(s):
word_count = 0
is_word = False
# Iterate through the string
for i in range(len(s)):
# Check if the character is a letter or escaped backslash and set is_word to True
if s[i].isalpha() or (s[i] == '\\' and i + 1 < len(s)): # Handle escaped backslash
is_word = True
# Skip the escaped character if it's a backslash
if s[i] == '\\':
i += 1
# Increment word_count if a word ends (space or end of string)
elif not s[i].isalpha() and not s[i].isdigit() and is_word: # Exclude digits for literal interpretation
word_count += 1
is_word = False
# Handle the last word (if it ends with a letter)
if is_word:
word_count += 1
return word_count
str = "abc\\p\""
print("No of words :", count_words(str))
# This code is contributed by kislay__kumar
C#
using System;
class Program
{
// Function to count total number of words in the string
static int CountWords(string str)
{
int wordCount = 0;
bool isWord = false;
// Iterate through the string
for (int i = 0; i < str.Length; i++)
{
// Check if the character is a letter or escaped backslash and set isWord to true
if (char.IsLetter(str[i]) || (str[i] == '\\' && i + 1 < str.Length)) // Handle escaped backslash
{
isWord = true;
// Skip the escaped character if it's a backslash
if (str[i] == '\\')
{
i++;
}
}
// Increment wordCount if a word ends (space or end of string)
else if (!char.IsLetter(str[i]) && !char.IsDigit(str[i]) && isWord) // Exclude digits for literal interpretation
{
wordCount++;
isWord = false;
}
}
// Handle the last word (if it ends with a letter)
if (isWord)
{
wordCount++;
}
return wordCount;
}
static void Main(string[] args)
{
string str = "abc\\p\"";
Console.WriteLine("No of words : " + CountWords(str));
}
}
// This code is contributed by kislay__kumar
Javascript
// Function to count total number of words in the string
function countWords(str) {
let wordCount = 0;
let isWord = false;
// Iterate through the string
for (let i = 0; i < str.length; i++) {
// Check if the character is a letter or escaped backslash and set isWord to true
if (/[a-zA-Z]/.test(str[i]) || (str[i] === '\\' && i + 1 < str.length)) { // Handle escaped backslash
isWord = true;
// Skip the escaped character if it's a backslash
if (str[i] === '\\') {
i++;
}
}
// Increment wordCount if a word ends (space or end of string)
else if (!/[a-zA-Z0-9]/.test(str[i]) && isWord) { // Exclude digits for literal interpretation
wordCount++;
isWord = false;
}
}
// Handle the last word (if it ends with a letter)
if (isWord) {
wordCount++;
}
return wordCount;
}
let str = "abc\\p\"";
console.log("No of words :", countWords(str));
// This code is contributed by kislay__kumar
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...