赞
踩
- 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 + ")");
- }
-
- }
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。