分別統計字符串內所有字符的個數

package Test05;

import java.util.HashSet;
import java.util.Set;

//用戶輸入字符串"If~you-want~to~change-your_fate_I_think~you~must~come-to-the-dark-horse-to-learn-java"
//程序輸出結果:-(9)I(2)_(3)a(7)c(2)d(1)e(6)f(2)g(1)h(4)i(1)j(1)k(2)l(1)m(2)n(4)o(8)r(4)s(2)t(8)u(4)v(1)w(1)y(3)~(6)
public class CharDemo {
	public static void main(String[] args) {
//思路:將字符串的每個字符存入Set集合,並進行去重。然後,遍歷累加輸出即可。
		String str = "If~you-want~to~change-your_fate_I_think~you~must~come-to-the-dark-horse-to-learn-java";
		// 字符數組
		char[] charArray = str.toCharArray();
		// 字符集合
		Set<Character> c = new HashSet<Character>();

		for (int i = 0; i < charArray.length; i++) {
			// 存入字符集合
			c.add(charArray[i]);
		}

		// 定義數組
		// String[] arr = c.toArray(new String[c.size()]);
		// System.out.println(Arrays.toString(arr));
		Character[] arr = c.toArray(new Character[c.size()]);
		for (int i = 0; i < arr.length; i++) {
			int count = 0;
			for (int j = 0; j < charArray.length; j++) {
				if (arr[i].equals(charArray[j])) {
					count++;
				}
			}
			System.out.print(arr[i] + "(" + count + ")");
		}

	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章