Java program to count number of words in a string
In this post, you will learn how to count number of words in a string using the Java programming language. These techniques find out how many times a given character is repeated in a given string.
Java program to count number of words in a string using for loop
In the given Java program, we use the for loop to count the words in a string.
import java.util.Scanner;
public class CountWords {
static int countwords(String string)
{
int count=0;
char ch[]= new char[string.length()];
for(int i=0;i0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!=' ')&&(i==0)))
count++;
}
return count;
}
public static void main(String[] args) {
String text;
Scanner SC=new Scanner(System.in);
System.out.print("Enter string: ");
text=SC.nextLine();
System.out.println("Number of words in a given string: "+countwords(text));
}
}
Output of the above code:
Enter string: Everyday is a chance to be better
Number of words in a given string: 7
Java program to count number of words in a string using while loop
In the given Java program, we use the while loop to count the words in a string.
import java.util.Scanner;
public class CountWords {
public static void main(String args[]) {
int flag = 0;
int count = 0;
int i = 0;
String text;
Scanner SC=new Scanner(System.in);
System.out.print("Enter string: ");
text=SC.nextLine();
while (i < text.length()) {
if (text.charAt(i) == ' ' || text.charAt(i) == ' ' || text.charAt(i) == '\t') {
flag = 0;
}else if (flag == 0) {
flag = 1;
count++;
}
i++;
}
System.out.println("Number of words in a given string: " + count);
}
}
Output of the above code:
Enter string: Work hard in silence
Number of words in a given string: 4
Related Articles
Java string split multiple delimitersEnum with values in Java
Convert array to list in Java
Java random number between 1 and 100
Calculating percentage in Java
Multiplication table program in Java
Java dialogue box
Fibonacci series using recursion in Java
Java sum of array
Circular prime in Java
Vowel and Consonant program in Java
Convert binary to decimal in Java
Convert decimal to binary in Java
Convert decimal to octal in Java
Convert decimal to hexadecimal in Java
Simple interest program in Java
Check whether the given number is even or odd in java
Print prime numbers from 1 to 100 in Java
Java prime number program
Java program to convert celsius to fahrenheit
Java program to check leap year
Java program to find factorial of a number