Java面試題之計算字符/字符串出現的次數

1、計算字符在給定字符串中出現的次數java

2、計算字符串在給定字符串中出現的次數spa

 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 }
相關文章
相關標籤/搜索