Count the number of occurrences of character c in a string in Java
Description
The following code shows how to count the number of occurrences of character c in a string.
Example
//from w w w.j a va 2 s . c o m
public class Main {
public static int countChar(String str, char c) {
int start = -1;
int count = 0;
while (true) {
if ((start = str.indexOf(c, start + 1)) == -1)
return (count);
count++;
}
}
public static void main(String[] argv) {
System.out.println(countChar("java2s.com",'a'));
}
}
The code above generates the following result.
Home »
Java Tutorial »
Java Data Type »
Java Tutorial »
Java Data Type »