A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

取出一个字符串中字母出现的次数。如:字符串:"abcdekka27qoq",输出格式为:a(2)b(1)k(2)...

7 个回复

倒序浏览
用map集合key存放字母,valu存放 该字符次数,集合中存在该字母,则value+1,不存在该字母则存入该字母,且value为1。
回复 使用道具 举报
用map集合啊 重复值加1
回复 使用道具 举报
TreeMap<Character, Integer> tm = new TreeMap<>();
                String s = "abcdekka27qoq";
               
                char[] arr = s.toCharArray();
                for (char c : arr) {
                        if(('a'<=c && c<='z') || ('A'<=c && c<='Z') ){
                                tm.put(c, !tm.containsKey(c)?1:tm.get(c)+1);
                        }
                }
                Set<Entry<Character,Integer>> entrySet = tm.entrySet();
               
                for (Entry<Character, Integer> entry : entrySet) {
                        System.out.print(entry.getKey() + "(" + entry.getValue() +")");
                }
回复 使用道具 举报
[Java] 纯文本查看 复制代码
import java.util.TreeMap;
/**
 * 
 * @author AnCheng
 *
 */
public class Test {

	public static void main(String[] args) {
		TreeMap<String, Integer> map = new TreeMap<>();
		String str = "abcdekka27qoq";
		for (int i = 0; i < str.length(); i++) {
			String s = str.charAt(i) + "";
			if (s.matches("[a-zA-Z]")) {
				map.put(s, map.containsKey(s) ? map.get(s) + 1 : 1);
			}
		}
		for (String key : map.keySet()) {
			int value = map.get(key);
			System.out.print(key + "(" + value + ")");
		}
	}

}
回复 使用道具 举报
本帖最后由 litianji2016 于 2016-9-16 12:13 编辑

/**
         * 可以利用集合HashSet,因为HashSet是存储无序不重复对象的!
         * @author litianji
         */
        public static void main(String[] args) {
                String str="abcdekka27qoq";//要用到的字符串
                char[] c=str.toCharArray();//转换为字符数组
                Arrays.sort(c);//排序
                Set set=new HashSet();
                /*
                 * 下面将字符数组存到ArrayList中和HashSet中,
                 */
                List list=new ArrayList();
                for (int i=0;i<c.length;i++) {
                        list.add(String.valueOf(c));
                        set.add(String.valueOf(c));
                }
                Iterator it=set.iterator();
                /*
                 * 从HashSet中取值去ArrayList中比较的值比较,
                 */
                while(it.hasNext()){
                        String s=(String)it.next();
                        int num=0;//当前字符出现的次数
                        for(int i=0;i<list.size();i++){
                                if(list.get(i).equals(s)){
                                        num++;
                                }
                        }
                        System.out.println(s+"("+num+")");
                        num=0;//完成一次比较,将num归零
                }
        }
回复 使用道具 举报
somnus-sir 发表于 2016-9-16 11:01
TreeMap tm = new TreeMap();
                String s = "abcdekka27qoq";
               

谢谢你啊,同学!
回复 使用道具 举报 1 0
谢谢分享,也是学习了
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马