count number of words in a string code example
Example 1: 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");
}
Example 2: how to count words in string
String str = "I am happy and why not
and why are you not happy and you should be";
String [] arr = str.split(" ");
Map<String, Integer> map = new HashMap<>();
for (int i=0 ; i < arr.length ; i++){
if (!map.containsKey(arr[i])){
map.put(arr[i],1);
} else{
map.put(arr[i],map.get(arr[i])+1);
}
}
for(Map.Entry<String, Integer> each : map.entrySet()){
System.out.println(each.getKey()+" occures " + each.getValue() + " times");
}
Example 3: how to count number of words in a string
String name = "Carmen is a fantastic play";
int numWords = (name.split("\\s+")).length;
System.out.println(numWords);
Example 4: program code for counting the similarwrod in the sentences
public static int count(String word) {
if (word == null || word.isEmpty()) {
return 0;
}
int wordCount = 0;
boolean isWord = false;
int endOfLine = word.length() - 1;
char[] characters = word.toCharArray();
for (int i = 0; i < characters.length; i++) {
if (Character.isLetter(characters[i]) && i != endOfLine) {
isWord = true;
} else if (!Character.isLetter(characters[i]) && isWord) {
wordCount++;
isWord = false;
} else if (Character.isLetter(characters[i]) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}