Java中得出字符串中每个字符串出现的次数

 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;  } }


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值