去重的几种方法

1.list方法:

public class Demo4 {
	public static String notRepest2(String str){
		ArrayList list = new ArrayList();
		String newsString="";
		for (int i = 0; i < str.length(); i++) {
			if (list.contains(str.charAt(i))==false) {
				list.add(str.charAt(i));
			}
		}
		for (Object obj : list) {
			newsString+=obj;
		}
		return newsString;
	}
	public static void main(String[] args) {
		System.out.println(Demo4.notRepest2("hyyydyhrjytutjujt"));
	}

}

输出结果:

2.set方法: 

public class Demo2 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("输入字符串:");
		String a = sc.next();
		char[] b = a.toCharArray();
		HashSet set = new HashSet();
		StringBuilder aaa = new StringBuilder();
		for (int i = 0; i < b.length; i++) {
			if(set.add(b[i])){
				aaa.append(b[i]);
			}
		}
		System.out.println(aaa);
	}

}

输出结果:

 3.HashMap方法:

public class Demo5 {
	public static String notrepeat5(String str){
		String result = "";
		Map map = new HashMap();
		for (int i = 0; i < str.length(); i++) {
			String a = str.charAt(i)+"";
			map.put(a, i);
		}
		Iterator iterator = map.keySet().iterator();
		while(iterator.hasNext()){
			result = result + iterator.next();
		}
		return result;
	}
	public static void main(String[] args) {
		Demo5 a = new Demo5();
		String b = a.notrepeat5("asdqwad");
		System.out.println(b);
	}

}

输出结果:

 

Guess you like

Origin blog.csdn.net/Cherishff/article/details/121786561