code to count all the words of each length in text java code example
Example 1: count the number of words in a string java
public static void main(String[] args)
{
String example = "This is a good exercise";
int length = example.split(" ").length;
System.out.println("The string is " + length + " words long.");
}
Example 2: count word in string no matter the delimiter java
public static void main(String[] args)
{
Scanner dude = new Scanner(System.in);
String string1 = "";
int count = 0;
boolean isWord = false;
System.out.println("Enter in your string");
string1 = dude.nextLine();
int endOfLine = string1.length()-1;
char ch [] = string1.toCharArray();
for (int i = 0; i < string1.length(); i++)
{
if(Character.isLetter(ch[i]) && i != endOfLine)
{
isWord = true;
}
if (!Character.isLetter(ch[i]) && isWord)
{
count++;
isWord = false;
}
if (Character.isLetter(ch[i]) && i == endOfLine)
{
count++;
isWord = false;
}
}
System.out.println("There are " +count+ " words");
}