count of element in string java code example
Example 1: count the number of words in a string java
public static void main(String[] args)
{
//return the number of words in a string
String example = "This is a good exercise";
int length = example.split(" ").length;
System.out.println("The string is " + length + " words long.");
}
Example 2: count the number of occurrences of a character in a string java
String line = "apples.oranges.bananas";
int count = line.length() - line.replace(".", "").length();
System.out.println(count);//displays 2