Simple way to count character occurrences in a string [duplicate]
public int countChar(String str, char c)
{
int count = 0;
for(int i=0; i < str.length(); i++)
{ if(str.charAt(i) == c)
count++;
}
return count;
}
This is definitely the fastest way. Regexes are much much slower here, and possible harder to understand.
Functional style (Java 8, just for fun):
str.chars().filter(num -> num == '$').count()
Not optimal, but simple way to count occurrences:
String s = "...";
int counter = s.split("\\$", -1).length - 1;
Note:
- Dollar sign is a special Regular Expression symbol, so it must be escaped with a backslash.
- A backslash is a special symbol for escape characters such as newlines, so it must be escaped with a backslash.
- The second argument of split prevents empty trailing strings from being removed.
You can use Apache Commons' StringUtils.countMatches(String string, String subStringToCount)
.