简体   繁体   English

Java内置方法 - 在字符串中出现char

[英]Java built-in method - occurrences of a char in a string

Is there a java built-in method to count occurrences of a char in a string ? 是否有一个java内置方法来计算字符串中char的出现次数? for example: s= "Hello My name is Joel" the number of occurrences of l is 3 例如: s= "Hello My name is Joel" l的出现次数是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
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM