软件编程
位置:首页>> 软件编程>> java编程>> Java编程实现统计一个字符串中各个字符出现次数的方法

Java编程实现统计一个字符串中各个字符出现次数的方法

作者:移动小狂人-赵子龙  发布时间:2023-01-24 18:02:20 

标签:Java,统计,字符串

本文实例讲述了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)+")");
   }
 }
}

运行结果:

Java编程实现统计一个字符串中各个字符出现次数的方法

PS:这里再为大家推荐2款非常方便的统计工具供大家参考使用:

在线字数统计工具:
http://tools.jb51.net/code/zishutongji

在线字符统计与编辑工具:
http://tools.jb51.net/code/char_tongji

希望本文所述对大家java程序设计有所帮助。

来源:http://blog.csdn.net/zl18603543572/article/details/46567685

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com