JAVA算法字符串统计

本文提供两种方法来统计一个字符串中不同字符的出现次数。方法一使用Java的HashMap来记录每个字符及其对应的出现次数,并遍历输出这些信息。方法二则通过自定义一个类T来存储字符和计数,利用ArrayList进行收集并打印结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 String s="asdsdfsdfasdasda";   
        int differentCount = 0;   
        Map<Character,Integer> map = new HashMap<Character,Integer>();   
        for(int i=0;i<s.length();i++){   
            Character c = new Character(s.charAt(i));   
            if(map.containsKey(c)){   
                map.put(c, map.get(c).intValue()+1);   
            }else{   
                map.put(c, new Integer(1));   
            }   
        }   
        Iterator<Character> it = map.keySet().iterator();   
        while(it.hasNext()){   
            Character tmpc = it.next();   
            differentCount++;   
            System.out.println(tmpc+"="+map.get(tmpc));   
        }   
        System.out.println("differentCount="+differentCount);  
-------------------------------------------------------------------------

方法2
/*  
 * To change this template, choose Tools | Templates  
 * and open the template in the editor.  
 */  
  
package mysrc;   
  
import java.util.*;   
/**  
 *  
 * @author yunchow  
 */  
public class Test {   
       
    public static void  main(String[] args){   
        char[] c = "asdsdfsdfasdasda".toCharArray();   
        List<T> list = new ArrayList<T>();   
        for(int i=0;i<c.length;i++){   
            if(!list.contains(new T(c[i])))   
                list.add(new T(c[i],1));   
            else{   
                T t = new T(c[i]);   
                for(int j=0;j<list.size();j++){   
                    if(t.equals(list.get(j))){   
                        t = list.get(j);   
                        t.setN(t.getN()+1);   
                    }   
                }   
            }   
        }   
        for(int t=0;t<list.size();t++){   
            T tt = new T();   
            tt = list.get(t);   
            System.out.println("The Char is : " + tt.getC() + ", The Num is : " + tt.getN());   
        }   
    }   
}   
class T {   
    private char c;   
    private int n;   
    public T(){}   
    public T(char a){   
        c = a;   
    }   
    public T(char a,int m){   
        c = a;   
        n = m;   
    }   
    public void setC(char arg){   
        c = arg;   
    }   
    public char getC(){   
        return c;   
    }   
    public void setN(int arg){   
        n = arg;   
    }   
    public int getN(){   
        return n;   
    }   
  
    @Override  
    public int hashCode() {   
        return this.c;   
    }   
  
    @Override  
    public boolean equals(Object obj) {   
        return this.hashCode() == obj.hashCode();   
    }   
       
}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值