String中每个字符出现的次数

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;
	}
}

阅读更多
个人分类: Java基础
上一篇求String的交集、并集、差集
下一篇ubuntu下安装jdk7
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭