java怎么计算一个字符在字符串中出现的次数
2个回答
展开全部
import java.util.*;
public class Test {
public static void main(String args[]){
String s = "abcdad"; //待测试的字符串
Map<Character, Integer> result = getCharMaps(s);
System.out.println(result);//打印出字符串中各字符出现的次数!
}
public static Map<Character, Integer> getCharMaps(String s) {
Map<Character, Integer> map = new HashMap<Character, Integer>();
for(int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
Integer count = map.get(c);
map.put(c, count == null ? 1 : count + 1);
}
return map;
}
}
public class Test {
public static void main(String args[]){
String s = "abcdad"; //待测试的字符串
Map<Character, Integer> result = getCharMaps(s);
System.out.println(result);//打印出字符串中各字符出现的次数!
}
public static Map<Character, Integer> getCharMaps(String s) {
Map<Character, Integer> map = new HashMap<Character, Integer>();
for(int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
Integer count = map.get(c);
map.put(c, count == null ? 1 : count + 1);
}
return map;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询