public class Demo {
public static void main(String[] args) {
String str = "albcad12l;''>sfg,?>";
String newStr = quChong5(str);
System.out.println(newStr);
}
}
//1.字符串
public static String quChong(String str){
String newStr = "";
for (int i = 0; i < str.length(); i++) {
String strs = str.charAt(i) + "";
if(newStr.indexOf(strs) == -1){
newStr = newStr + strs;
}
}
return newStr;
}
//2.set
public static String quChong2(String str){
Set set = new HashSet();
for (int i = 0; i < str.length(); i++) {
String strs = str.charAt(i) + "";
set.add(strs);
}
String result = toString(set);
return result;
}
public static String toString(Set set){
String result = "";
for (Object object : set) {
result = result + (String)object;
}
return result;
}
//3.list
public static String quChong3(String str){
List list = new ArrayList();
for (int i = 0; i < str.length(); i++) {
String strs = str.charAt(i) + "";
if(!list.contains(strs)){
list.add(strs);
}
}
String newStr = toString(list);
return newStr;
}
public static String toString(List list){
String result = "";
for (int i = 0; i < list.size(); i++) {
result = result + list.get(i);
}
return result;
}
//4.hashMap
public static String quChong4(String str){
Map map = new HashMap();
for (int i = 0; i < str.length(); i++) {
String strs = str.charAt(i) +"";
map.put(strs, 1);
}
Set set = map.keySet();
String result = toString(set);
return result;
}
public static String toString2(Set set) {
String result = "";
for (Object object : set) {
result = result + (String)object;
}
return result;
}
//5.字符串数组
//[a,b,c,a,b,f,g]
public static String quChong5(String str){
//定义一个数组
//把传进来字符串的每个字符放在数组里
String[] strs = new String[str.length()];
for (int i = 0; i < strs.length; i++) {
String s = str.charAt(i)+"";
strs[i] = s;
}
//数组里如果有重复的,把重复的字符串赋值成随便定义的字符串(目的:遍历这个数组,把这个数组中不等于随便定义的那个字符串的所有字符串放在重新定义的新数组中)
for (int i = 0; i < strs.length - 1; i++) {
for (int j = i + 1; j < strs.length; j++) {
if(strs[i].equals(strs[j])){
strs[j] = str;
}
}
}
//找出不重复的所有字符串的个数
int count = 0;
for (int i = 0; i < strs.length; i++) {
if(strs[i].equals(str)){
count = count + 1;
}
}
//定义一个新数组(已算出新数组的长度)
//把不重复的字符串放进新数组中
String newstr = "";
int newCount = str.length()-count;
int index = 0;
String[] newStrings = new String[newCount];
for (int i = 0; i < strs.length; i++) {
if(!strs[i].equals(str)){
newStrings[index] = strs[i];
index = index++;
newstr = newstr + strs[i];
}
}
return newstr;
}