Is there a java built-in method to count occurrences of a char in a string ?
for example:
s= "Hello My name is Joel"
the number of occurrences of l
is 3
Thanks
Is there a java built-in method to count occurrences of a char in a string ?
for example:
s= "Hello My name is Joel"
the number of occurrences of l
is 3
Thanks
There is no such method, but you can do:
String s = "Hello My name is Joel";
int counter = 0;
for( int i=0; i<s.length(); i++ ) {
if( s.charAt(i) == 'l' ) {
counter++;
}
}
(code from Simple way to count character occurrences in a string)
If you want to count the number of times multiple characters have appeared in a particular string, then mapping of characters with their number of occurrences in the string will be a good option. Here's how one would achieve the solution in that case:
import java.util.HashMap;
import java.util.Map;
public class CharacterMapper
{
private Map<Character, Integer> charCountMap;
public CharacterMapper(String s)
{
initializeCharCountMap(s);
}
private void initializeCharCountMap(String s)
{
charCountMap = new HashMap<>();
for (int i = 0; i < s.length(); i++)
{
char ch = s.charAt(i);
if (!charCountMap.containsKey(ch))
{
charCountMap.put(ch, 1);
}
else
{
charCountMap.put(ch, charCountMap.get(ch) + 1);
}
}
}
public int getCountOf(char ch)
{
if (charCountMap.containsKey(ch))
return charCountMap.get(ch);
return 0;
}
public static void main(String[] args)
{
CharacterMapper ob = new CharacterMapper("Hello My name is Joel");
System.out.println(ob.getCountOf('o')); // Prints 2
}
}