1、使用HaspMap的键值来存储“字符”及“字符次数”:
String str = "1122345678";
HashMap<Character, Integer> strhash = new HashMap<Character, Integer>();
int num = 0;
int count = 0;
for (int i = 0; i <= str.length() - 1; i++) {
char c = str.charAt(i);
int temp = 0;
for (int j = 0; j <= str.length() - 1; j++) {
num = str.indexOf(c, temp);
if (num != -1) {
count++;
temp = num + 1;
continue;
}
else {
strhash.put(c, count);
count = 0;
break;
}
}
}
/*Iterator iter = strhash.entrySet().iterator();// 返回一个set集合
while (iter.hasNext()) {
Map.Entry<Character, Integer> entry = (Map.Entry<Character, Integer>) iter
.next();
Object key = entry.getKey();
Object value = entry.getValue();
System.out.println(key + "=" + value);
} */
Iterator iter1 = strhash.keySet().iterator();
while (iter1.hasNext()) {
Object key = iter1.next();
Object value = strhash.get(key);
System.err.println(key + "=" + value);
}
2、把字符中每个字符先取出来(使用递归的方式),然后循环查询次数,效率上比第一种差,但是好理解。
public class Test {
char array_char[];
List lists=new ArrayList();
public int getInstances(String all, String choice) {
int total=0;
array_char=all.toCharArray();
for(int i=0;i<array_char.length;i++){
if (array_char[i]==(choice.charAt(0))){
total++;
}
}
return total;
}
public static void main(String[] args) {
Test test=new Test();
String str="144745741258444174584";
List array=test.result(str);
for(int i=0;i<array.size();i++)
{
System.out.println(array.get(i)+" 出现的次数:"+test.getInstances(str, array.get(i).toString()));
}
}
public List result(String str)
{
String st="";
if(str.length()>0)
{
lists.add(str.substring(0,1));
st=str.replaceAll(str.substring(0,1),"");
result(st);
}
return lists;
}
}