Wednesday, January 19, 2011

Howto count chars in a String

This code snippet demonstrates a simple way to count the number of occurrences of a specific char:


public static int countNumberOfCharsInString(Char c, String s){
String regex = "[^" + c + "]";

return s.replaceAll(regex, "").length();
}
The regular expression matches on the char given, which results in a String, generated from the call to replaceAll, that only contains the specified char.
The call to length therefore results in the number chars in the given String.

No comments: