package Bean;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class CountChars {
public static void main(String[] args) {
// String str = "ababbbcsg";
// String subStr = "abb";
// int num = str.indexOf(subStr);
// System.out.println(num);
Scanner sc = new Scanner(System.in);
System.out.println("Please Input Your String!");
String str = sc.nextLine();
Map<Character, Integer> map = countLetters(str);
System.out.println("total kinds: " + map.size());
for (Map.Entry<Character, Integer> entry : map.entrySet()) { // 增强的for循环
System.out.printf("letter %c: %d\n", entry.getKey(), entry
.getValue());
}
}
static Map<Character, Integer> countLetters(String s) {
if (s == null) {
return null;
}
Map<Character, Integer> map = new HashMap<Character, Integer>();
char c;
Integer oldValue;
int newValue;
for (int i = 0; i < s.length(); ++i) {
c = s.charAt(i);
oldValue = map.get(c);
newValue = (oldValue == null) ? 1 : oldValue.intValue() + 1;
map.put(c, newValue);
}
return map;
}
}
String中每个字符出现的次数
最新推荐文章于 2022-06-23 10:42:12 发布