package com.webkfa.test; import java.io.IOException; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class Test { public static void main(String[] args) throws IOException{ String webkfastr=jscharsum("Adfdafdsafsafdsafdsafdsafdsa"); System.out.println("运行结果:"+webkfastr); //运行结果:f(7)d(7)s(6)A(1)a(7) } /** * java获得字母出现的次数 * @param str * @return a(3)c(2)... */ public static String jscharsum(String str){ if(str==null || "".equals(str)){ return "你传的参数为空"; } StringBuffer sb=new StringBuffer(); //用java里面的set去重 Set<String> set=new HashSet<String>(); for (int i = 0; i < str.length(); i++) { char c=str.charAt(i); set.add(String.valueOf(c)); } Iterator<String> it =set.iterator(); while (it.hasNext()) { String s = it.next(); int csum=0; for (int i = 0; i < str.length(); i++) { char c=str.charAt(i); if(s.equals(String.valueOf(c))){ csum++; } } sb.append(s+"("+csum+")"); } return sb.toString(); } }