标签:string stat rem imp 数组 for main \n ring
java去除字符串中重复、不重复、消除重复后字符import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
String str = "aaasd";
System.out.println("原字符串: "+str);
Set<Character> set1 = new HashSet<Character>();
Set<Character> set2 = new HashSet<Character>();
Set<Character> set3 = new HashSet<Character>();
//把字符串转为字符数组
char[] cs = str.toCharArray();
//便利字符数组aaasd
for(char c:cs){
//把遍历的字符加入set1(HashSet,无序不可重复)
boolean b = set1.add(c);//asd
if(!b){
//b不等空就是有重复的字符,重复的字符加入set2
set2.add(c);//a
}
}
//把消除重复后的字符set1赋给Set3
set3.addAll(set1);//asd
//把消除的重复后的字符set1 - 重复的字符set2 = 不重复的字符
set3.removeAll(set2);//asd-a = sd
System.out.println("=========消除重复厚的字符=========");
for ( char c : set1){
System.out.print(c + "");
}
System.out.println("\n===========重复的字符===============");
for (char c :set2){
System.out.print(c + "");
}
System.out.println("\n========不重复的数组===========");
for (char c :set3){
System.out.print(c + "");
}
}
}
标签:string stat rem imp 数组 for main \n ring
原文地址:http://blog.51cto.com/13579083/2329972