Java编程实现统计一个字符串中各个字符出现次数的方法
作者:移动小狂人-赵子龙 时间:2023-01-24 18:02:20
本文实例讲述了Java编程实现统计一个字符串中各个字符出现次数的方法。分享给大家供大家参考,具体如下:
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
public class TreeMapDemo
{
//统计一个字符串中相应字符出现的次数
public static void main(String[] args)
{
//
System.out.println("脚本之家测试结果:");
String s = "aagfagdlkerjgavpofjmvglk我是你的";
//调用自定义方法来 统计相应字符出现的次数
method(s);
}
private static void method(String s)
{
//定义 一个容器
TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
//将这TreeMap中的key全部取出来,然后储存到set集合中去
Set<Character> st = tm.keySet();
//将所需要统计的字符串转换成一个字符数组
char[] c = s.toCharArray();
//通过for循环逐一统计每个字符出现的次数
for(int x=0;x<c.length;x++)
{
if(!st.contains(c[x]))
{
tm.put(c[x], 1);
}
else
{
tm.put(c[x], tm.get(c[x])+1);
}
}
//调用自定义方法在控制台上输出统计信息
printMapDemo(tm);
}
private static void printMapDemo(TreeMap<Character, Integer> tm) {
// TODO Auto-generated method stub
Set<Character> st = tm.keySet();
Iterator<Character> ti = st.iterator();
for(;ti.hasNext();)
{
char key = ti.next();
System.out.println(key+"("+tm.get(key)+")");
}
}
}
运行结果:
PS:这里再为大家推荐2款非常方便的统计工具供大家参考使用:
在线字数统计工具:
http://tools.jb51.net/code/zishutongji
在线字符统计与编辑工具:
http://tools.jb51.net/code/char_tongji
希望本文所述对大家java程序设计有所帮助。
来源:http://blog.csdn.net/zl18603543572/article/details/46567685
标签:Java,统计,字符串
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Flutter有无状态类与State及生命周期详细介绍
2022-12-27 15:48:53
![](https://img.aspxhome.com/file/2023/9/139629_0s.png)
MybatisPlus字段类型转换的实现示例
2022-12-09 22:29:13
![](https://img.aspxhome.com/file/2023/6/78906_0s.jpg)
JavaBean和SpringBean的区别及创建SpringBean方式
2022-05-23 03:32:14
springboot整合RabbitMQ 中的 TTL实例代码
2022-04-18 03:12:34
![](https://img.aspxhome.com/file/2023/3/103983_0s.png)
Java泛型的使用限制实例分析
2023-05-07 20:14:52
springboot结合maven实现多模块打包
2022-01-16 07:13:51
javascript checkbox全选和反选的简单实现
2022-08-31 14:16:32
C#操作session的类实例
2023-07-17 13:57:19
mybatis中的缓存问题解析
2023-07-27 20:01:59
![](https://img.aspxhome.com/file/2023/0/103820_0s.png)
C#仿QQ聊天窗口
2022-09-30 09:12:39
![](https://img.aspxhome.com/file/2023/3/69823_0s.jpg)
C# 使用Log4net添加日志记录的方法
2021-11-16 01:57:23
![](https://img.aspxhome.com/file/2023/6/106446_0s.png)
Spring cloud alibaba之Ribbon负载均衡实现方案
2021-11-08 20:05:23
![](https://img.aspxhome.com/file/2023/5/83005_0s.png)
SpringBoot全局异常与数据校验的方法
2023-12-11 10:46:06
![](https://img.aspxhome.com/file/2023/3/76623_0s.png)
Android开发中ImageLoder加载网络图片时将图片设置为ImageView背景的方法
2021-12-14 14:58:38
Java调用Oracle存储过程详解
2022-09-09 03:19:45
SpringBoot配置mybatis驼峰命名规则自动转换的实现
2023-07-26 17:47:43
Spring容器初始化及问题解决方案
2023-09-14 08:19:32
C#利用控件拖拽技术制作拼图游戏
2023-05-24 21:27:34
C#使用二分查找法判断指定字符的方法
2022-08-02 06:46:30
C++编程中的const关键字常见用法总结
2023-12-02 17:41:48