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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM