1

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

mr.pppoe
  • 3,945
  • 1
  • 19
  • 23
TomM12
  • 55
  • 1
  • 8
  • I dont think so. You can iterate over the char array from the string (toCharArray()) and use a Map for counting. If Key exists count integer one up, else new Entry with startvalue 1. If you search a single char only... use REGEX : http://stackoverflow.com/questions/6100712/simple-way-to-count-character-occurrences-in-a-string – pL4Gu33 Mar 01 '14 at 16:38
  • Good application for a guava [`Multiset`](https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained) –  Mar 01 '14 at 17:07
  • @RC: If you're going to use Guava, you might as well do it in the one-liner `CharMatcher.is('l').countIn(string)`. – Louis Wasserman Mar 01 '14 at 20:05
  • @LouisWasserman if you only need count for `l` sure –  Mar 01 '14 at 20:24

2 Answers2

3

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)

Community
  • 1
  • 1
user123454321
  • 1,028
  • 8
  • 26
0

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
  }
}
Aman Agnihotri
  • 2,973
  • 1
  • 18
  • 22