JavaHashset字符串练习

第四题:HashSet的应用
编写程序,给定字符串,如:
String str = “abaacdebbafblmbffnoeeepawc”;
输出其中重复的字符、不重复的字符以及消除重复以后的字符列表。
比如:
原字符串:abaacdebbafblmbffnoeeepawc
消除重复后的字符====
p a b c d e f w l m n o
重复的字符====
a b c e f
不重复的字符====
p d w l m n o

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

public class Main {
	public static void main(String[] args) {
		String str = "abaacdebbafblmbffnoeeepawc";
		Set s = new HashSet();//用来记录去重的字符
		Set s1 = new HashSet();//用来记录重复的字符
		Set s2 = new HashSet();//用来记录不重复的字符
		char  ch[] = str.toCharArray();
		for(char c : ch) {
			boolean b = s.add(c);
			if(!b) {
				s1.add(c);
			}
		}
		s2.addAll(s);//去重后的字符串
		s2.removeAll(s1);//再去掉重复的字符串
		//去重后的字符串
		System.out.println("原字符串:"+str);
		System.out.println("====消除重复后的字符========");
		for(char c :s) {
			System.out.print(c+" ");
		}
		System.out.println();
		System.out.println("====重复的字符========");
		for(char c :s1) {
			System.out.print(c+" ");
		}
		System.out.println();
		System.out.println("====不重复的字符========");
		for(char c :s2) {
			System.out.print(c+" ");
		}
	}
}

你可能感兴趣的:(Java)