1 import java.util.ArrayList; 2 import java.util.HashSet; 3 import java.util.Iterator; 4 import java.util.List; 5 import java.util.Set; 6 7 /** 8 * 9 * @author trfizeng 10 */ 11 public class CountStr { 12 13 //统计任意字符串出现的次数 14 public static List<String> countStr(String str) { 15 //用于存放生成要检测的字符串的字典 16 Set<String> base = new HashSet<String>(); 17 //用于存放输入的字符串的每个字符 18 List<String> totalStr = new ArrayList<String>(); 19 //用于存放每个字符出现的次数 20 List<String> couList = new ArrayList<String>(); 21 //把字符串转化为字符数组 22 char [] tempChar = str.toCharArray(); 23 24 //初始化字典和要统计的字符 25 for (int i = 0; i < tempChar.length; i++) { 26 base.add(tempChar[i]+""); 27 totalStr.add(tempChar[i]+""); 28 } 29 30 Iterator<String> it = base.iterator(); 31 //初始化每个字符出现的次数 32 while (it.hasNext()) { 33 String string = (String) it.next(); 34 couList.add(string + ":" + 0); 35 } 36 37 //用于计数每个字符出现的次数 38 int c = 0; 39 //开始遍历 40 for (int i = 0; i < totalStr.size(); i++) { 41 String tC = totalStr.get(i); 42 Iterator<String> ite = base.iterator(); 43 while (ite.hasNext()) { 44 String obj = ite.next(); 45 //判断字符是否出现 46 if (tC.equals(obj)) { 47 for (int j = 0; j < couList.size(); j++) { 48 String cL = couList.get(j); 49 if (cL.startsWith(obj)) { 50 //把原来出现的次数拿出来+1 51 c = Integer.parseInt(cL.substring(cL.lastIndexOf(":")+1,cL.length())); 52 c++; 53 //从新设置出现的次数 54 couList.set(j, obj + ":" + (c)); 55 } 56 } 57 } 58 } 59 } 60 return couList; 61 } 62 63 public static void main(String[] args) { 64 String testStr = "dfe:RRxc.:./哈哈有:"; 65 List<String> cList = countStr(testStr); 66 for (int i = 0; i < cList.size(); i++) { 67 System.out.print(cList.get(i) + " "); 68 } 69 /* 70 * 71 char []c=testStr.toCharArray(); 72 Map<String,Integer> m=new HashMap<String, Integer>(); 73 for(int i=0;i<c.length;i++){ 74 String cstr=String.valueOf(c[i]); 75 if(null!=m.get(cstr)){ 76 int count=m.get(cstr); 77 m.put(cstr, count+1); 78 }else{ 79 m.put(cstr,1); 80 } 81 } 82 83 */ 84 } 85 }
d:1 /:1 R:2 ::3 c:1 哈:2 f:1 .:2 x:1 有:1 e:1
时间: 2024-10-17 23:24:52