统计字符串中每个字符在字符串中出现的次数
2012-05-15 15:59:31 来源:WEB开发网核心提示:package com.taoniwu.io;import java.util.*;public class SrSearch {/** * @param args */public static void main(String[] args) {String sr = "sdjwiwdnwiedaaaas
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;
}
}
更多精彩
赞助商链接
