- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to count words in a given string
The words in a given string can be counted using a while loop. An example of this is given as follows −
String = Sky is blue Number of words = 3
A program that demonstrates this is given as follows.
Example
public class Example { public static void main(String args[]) { int flag = 0; int count = 0; int i = 0; String str = "The sunset is beautiful"; while (i < str.length()) { if (str.charAt(i) == ' ' || str.charAt(i) == '
' || str.charAt(i) == '\t') { flag = 0; }else if (flag == 0) { flag = 1; count++; } i++; } System.out.println("The string is: " + str); System.out.println("No of words in the above string are: " + count); } }
The output of the above program is as follows.
Output
The string is : The sunset is beautiful No of words in the above string are : 4
Now let us understand the above program.
First, the string str is defined. Then a while loop is used to obtain the number of words in the string. This is done using the flag variable that is initially initialized to 0. The code snippet that demonstrates this is given as follows.
int flag = 0; int count = 0; int i = 0; String str = "The sunset is beautiful"; while (i < str.length()) { if (str.charAt(i) == ' ' || str.charAt(i) == '
' || str.charAt(i) == '\t') { flag = 0; }else if (flag == 0) { flag = 1; count++; } i++; }
Finally, the string and the number of words in it are displayed. The code snippet that demonstrates this is given as follows.
System.out.println("The string is: " + str); System.out.println("No of words in the above string are: " + count);
- Related Articles
- Python program to Count words in a given string?
- C# program to Count words in a given string
- Java Program to count the number of words in a String
- Count words in a given string in C++
- How to count a number of words in given string in JavaScript?
- Reverse words in a given String in Java
- C# program to count the number of words in a string
- Java program to count upper and lower case characters in a given string
- Java Program to count letters in a String
- Java Program to count vowels in a string
- Python program to count words in a sentence
- Java Program to count all vowels in a string
- Java Program to Print all unique words of a String
- Python Program to Count the Frequency of Words Appearing in a String Using a Dictionary
- Java program to count occurrences of a word in string

Advertisements