bayes

本程序演示从一个字符串中找出重复的字符,并显示重复字符的个数。

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
 
public class Details {
 
  public void countDupChars(String str){
 
    //创建一个HashMap对象
    Map<Character, Integer> map = new HashMap<Character, Integer>(); 
 
    //将字符串转换为char数组
    char[] chars = str.toCharArray();
 
    /* logic: 将每个字符插入到map中,map中的每个元素是[key,value]的组合,
     * key记录字符,value记录这个字符出现的次数。
     * 如果map中已经存在ch,则修改该字符出现的次数(原来次数+1)。
     * 如果map中还没有ch,则将ch插入到map中,key为ch的值,value为1*/
    for(Character ch:chars){
      if(map.containsKey(ch)){
         map.put(ch, map.get(ch)+1);
      } else {
         map.put(ch, 1);
        }
    }
 
    //获得map的键集
    Set<Character> keys = map.keySet();
 
    /* 对出现超过1次的字符,显示其个数.
     */
    for(Character ch:keys){
int n = map.get(ch);//从map中获取ch的个数
if(n > 1){ System.out.println("Char "+ch+" "+n); } } } public static void main(String a[]){ Details obj = new Details(); System.out.println("String: www.google.com"); System.out.println("-------------------------"); obj.countDupChars("www.google.com"); System.out.println("\nString: Hello World"); System.out.println("-------------------------"); obj.countDupChars("Hello World"); System.out.println("\nString: #@$@!#$%!!%@"); System.out.println("-------------------------"); obj.countDupChars("#@$@!#$%!!%@"); } }

 

分类:

技术点:

相关文章:

  • 2021-11-17
  • 2022-12-23
  • 2021-11-30
  • 2022-01-18
  • 2022-12-23
  • 2022-12-23
  • 2022-01-26
  • 2022-12-23
猜你喜欢
  • 2021-11-05
  • 2022-12-23
  • 2021-06-24
  • 2022-12-23
  • 2021-10-27
  • 2021-11-24
  • 2022-12-23
相关资源
相似解决方案