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

4
  • I dont think so. You can iterate over the char array from the string (toCharArray()) and use a Map<String, Integer> for counting. If Key exists count integer one up, else new Entry with startvalue 1. If you search a single char only... use REGEX : stackoverflow.com/questions/6100712/… Commented Mar 1, 2014 at 16:38
  • Good application for a guava Multiset Commented Mar 1, 2014 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). Commented Mar 1, 2014 at 20:05
  • @LouisWasserman if you only need count for l sure Commented Mar 1, 2014 at 20:24

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.