Louis I. answered 03/21/19
Computer Science Instructor/Tutor: Real World and Academia Experienced
There are no String methods, or any other core-java methods for that matter, that provides an occurrence count - and therefore, a one line solution.
However, Java 8 offers 'Lambda Function' magic - and therefore the following code fragment works.
This displayed: " '.' Count: 6 "
public static void main(String[] args) {
String myString = "a.b.c.d.e.f.g";
long count = myString.chars().filter(charCount -> charCount == '.').count(); /// <<<<<<<
System.out.printf("'.' Count: %d\n", count);
}
It's difficult to explain without getting into Lambda Expressions - but let's just say that the 3rd line above is assigned a filter count - and we're filtering by characters that equal "."
I could change the code above to the following and get a count of 12.
You see why, right?
public static void main(String[] args) {
String myString = "a.b.c.d.e.f.g";
long count = myString.chars().filter(charCount -> charCount != 'f').count();
System.out.printf("'.' Count: %d\n", count);
}
Otherwise, you can of course do this the brute force way using a loop - or recursion.
Good luck.
--Lou