• Java面试题之计算字符/字符串出现的次数


    一、计算字符在给定字符串中出现的次数

    二、计算字符串在给定字符串中出现的次数

     1 import java.util.HashMap;
     2 import java.util.Map;
     3 
     4 public class Demo {
     5     public static void main(String[] args) {
     6         String str = "abcabdabc";
     7         //计算给定字符串中每个字符出现的次数
     8         findCharCount(str);
     9         //计算给定字符串在 目标字符串中的次数
    10         findCount(str, "ab");
    11     }
    12     //计算给定字符串中每个字符出现的次数
    13     public static void findCharCount(String str) {
    14         Map<Character,Integer> map = new HashMap<>();
    15         for(int i=0;i<str.length();i++) {
    16             char ch = str.charAt(i);
    17             //判断map容器中是否包含key
    18             if(map.containsKey(ch)) {
    19                 //如果集合中已经存在
    20                 Integer count = map.get(ch);
    21                 count += 1;
    22                 //重新存入
    23                 map.put(ch, count);
    24             }else {
    25                 map.put(ch,1);
    26             }
    27         }
    28         for (Character key : map.keySet()) {
    29             Integer value = map.get(key);
    30             System.out.println(key+" 出现了 "+value+" 次");
    31         }
    32     }
    33     //计算字符串在给定字符串出现的次数
    34     public static void findCount(String src,String des) {
    35         int index = 0;
    36         int count = 0;
    37         while((index = src.indexOf(des, index)) != -1) {
    38             count++;
    39             index = index + des.length();
    40         }
    41         System.out.println(des+"出现了 "+count+" 次");
    42     }
    43 }
  • 相关阅读:
    CentOS随笔
    CentOS随笔
    CentOS随笔
    CentOS随笔
    产品从生到死的N宗罪
    即将结束的2015。
    Mvvm
    android 热补丁修复框架
    反编译APK
    关于短视频
  • 原文地址:https://www.cnblogs.com/cat-fish6/p/8603533.html
Copyright © 2020-2023  润新知