`
u011936142
  • 浏览: 42686 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

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

 
阅读更多
package day07;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;

public class TongJiZiFuGeShu {

	/**
	 * @param str
	 * @param args
	 *            计数给I定字符串中每个元素的出现次数
	 */

	public void countChrNum(String str) {

		char[] stch = str.toCharArray();// 先转换成字符串数组
		Arrays.sort(stch);// 进行排序

		String str2 = new String(stch);// 再转换成String字符串
		HashMap<Character, Integer> count = new HashMap<Character, Integer>();

		for (int i = 0; i < str2.length(); i++) {
			char ch = str2.charAt(i);
			int begin = str2.indexOf(ch);// 获取出现给定字符的第一个索引
			int end = str2.lastIndexOf(ch);// 获取出现给定字符出现的最后一个下标索引
			if (count.containsKey(ch)) {// 判断是否已近存在这样一个键

			} else {
				count.put(ch, end - begin + 1);// 每次循环都进行记录
			}
		}

		Iterator itr = count.keySet().iterator();// 迭代出count中的键值

		while (itr.hasNext()) {// 判断是否还有下一个元素
			Object key = itr.next();// 让key每次都等于下一个元素的键值
			System.out.println(key + "出现了:" + count.get(key));// 根据键值输出

		}

	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str = "qqqwwwuuuuuu";
		TongJiZiFuGeShu countstr = new TongJiZiFuGeShu();
		countstr.countChrNum(str);
	}

}


//另外一种方法
package day02work;


import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;


public class Statistcs_Word {


	/**
	 * 统计一串字符串中每个字符出现的次数
	 *
	 * @param args
	 */


	public static void getNumber(String str) {// 单独定义一个方法来得到,字符出现次数
		int notWord = 0;// 用来计数字符出现次数
		int c = str.length();// 得到传入字符串的长度,后面用于循环计数用


		String word = "";// 接收非字母非数字的字符
		String words = "";// 接收字母和数字


		for (int i = 0; i < c; i++) {// 将字母和数字与其他字符分离
			if (!(str.charAt(i) >= 'A' && str.charAt(i) <= 'Z')
					&& !(str.charAt(i) >= 'a' && str.charAt(i) <= 'z')
					&& !(str.charAt(i) >= '0' && str.charAt(i) <= 9)) {
				notWord++;// 计数不是字母和数字的字符
			} else {
				word += str.charAt(i);// 将是字符和数字的字符重新连接
			}
		}


		Map<Character, Integer> outmu = new TreeMap<Character, Integer>();// 使用"键-值",这样可以接收出现的字符,也可以接收出现次数


		for (int j = 0; j < word.length(); j++) {
			int countWord = 0;
			for (int i = 0; i < word.length(); i++) {
				if (word.charAt(j) == word.charAt(i)) {
					countWord++;
				}
			}
			outmu.put(word.charAt(j), countWord);
		}
		Iterator itr = outmu.keySet().iterator();


		while (itr.hasNext()) {
			Object key = itr.next();
			System.out.println(key + "出现" + outmu.get(key) + "次");
		}
		System.out.println();
		System.out.println("非字母非数字的有:" + notWord + "个");


	}


	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Statistcs_Word.getNumber("abbcccddd");
	}


}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics