统计字符串中字符出现的次数//通俗易懂!!!

话不多说!
先看小题!!
如下字符串:
String str = “The String class represents character strings. All string literals in Java programs, are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.”;
统计各个字符出现的次数,-----------------并排序!!!

(方法不是唯一的,适合自己的或者更易理解的才是前期学习java的通路)

小解方式一:
使用HashMap或者TreeMap===========================================>>>>>>>>

    public void test3(){
        String str = "The String class represents character strings. All string literals in Java programs, are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.";
        //String replace = str.replace(" ", "");//去掉空格,如果不想比较空格/符号之类的可以使用这句代码/后面代码str改为replace
        char[] chars = str.toCharArray();
        //字符出现的次数,排序
        Map<Character,Integer> map = new TreeMap<>();
        for (int i = 0; i <chars.length ; i++) {
            if(!map.containsKey(chars[i])){
                map.put(chars[i],1);//键值对---key-->出现的字符
            }else{							//value-->同个字符出现的次数
                map.put(chars[i],map.get(chars[i]) +1);
            }
        }
        List<Map.Entry<Character,Integer>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {//使用比较器比较value的大小排序
            @Override
            public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
                return -o1.getValue().compareTo(o2.getValue());
            }
        });
        for(Map.Entry<Character,Integer> entry : list){
            System.out.println(entry.getKey() + "=" + entry.getValue());
        }
    }


在这里插入图片描述
小解方式二:
使用io流:====================================================>>>>>>>>>>>>>>>

public class MyStringTest {
    @Test
    public void test1(){
        String str = " ai bbiadg 字符 数字 汉字 符合 其他 .'',/';][%%$#@!&*()_+ ";
        FileWriter fw = null;
        try {
            fw = new FileWriter(new File("MyStringTest.txt"));//一步到位,创建字符输出流
            fw.write(str.toCharArray());//将字符串写入一个文件
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(fw != null)
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Test
    public void test2(){

        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            Map<Character,Integer> map = new HashMap<>();//使用Map便于保存 字符--次数
            br = new BufferedReader(new FileReader("MyStringTest.txt"));//创建字符输入缓冲流
            int len = 0;
            while ((len = br.read()) != -1){//读取文件中的内容,返回-1表示读取完毕
                char ch = (char)len;

                if(!map.containsKey(map.get(ch))){//统计各个字符出现的次数
                    map.put(ch,1);
                }else{
                    map.put(ch,map.get(ch) + 1);
                }
            }
            bw = new BufferedWriter(new FileWriter("MyStringCount.txt"));//创建字符输出缓冲流
            Set<Map.Entry<Character, Integer>> entrySet = map.entrySet();
            for(Map.Entry<Character,Integer> entry : entrySet){//增强for遍历集合
                switch (entry.getKey()){
                    case ' ':
                        bw.write("空格=" + entry.getValue());//依次写出key--value
                        break;
                    case '\t':
                        bw.write("tab=" + entry.getValue());
                        break;
                    case '\r':
                        bw.write("回车=" + entry.getValue());
                        break;
                    case '\n':
                        bw.write("换行=" + entry.getValue());
                        break;
                    default:
                        bw.write(entry.getKey() + "=" + entry.getValue());
                        break;
                }
                bw.newLine();//换行操作
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(bw != null){
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(br != null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

在这里插入图片描述
点赞或者评论,让弯路往前稍稍
有问题可以留言或者私信,看到后第一时间回复
初学或者零基础者的弯路!
在这里插入图片描述
下篇文章见!

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值