欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

统计字符串中每个字符在字符串中出现的次数。,字符串字符,统计字符串中每个字符在字

来源: javaer 分享于  点击 12211 次 点评:11

统计字符串中每个字符在字符串中出现的次数。,字符串字符,统计字符串中每个字符在字


统计字符串中每个字符在字符串中出现的次数。

package com.taoniwu.io;import java.util.*;public class SrSearch {    /**     * @param args     */    public static void main(String[] args) {        String sr = "sdjwiwdnwiedaaaasieesieassewe";        //创建一个HashMap容器        Map<Character,Integer> m = new HashMap<Character,Integer>();        //通过循环获取每个字符进行统计        for(int i=0;i<sr.length();i++){            char c = sr.charAt(i);            //调用方法search计算字符c在sr中出现的次数            int sum = search(sr,c);            m.put(c,sum);        }        System.out.println(m);    }    //在字符串sr中搜索字符ar出现的次数    public static int search(String sr,char ar){        int count = 0;        int num = 0;        int temp = 0;        while((sr.length()-temp) >= 1){            num = sr.indexOf(ar,temp);              //在字符串sr中,从temp个开始搜索ar,返回ar第一次出现的位置            if(num == -1){                temp = sr.length();             }            else{                temp = num + 1;                count++;                }        }        return count;    }}//该片段来自于http://byrx.net
相关栏目:

用户点评