刪除字串和陣列中重複的字元
阿新 • • 發佈:2018-12-16
刪除重複的字串
方法一(該方法只能判斷連續的字串)
public class Delzi { public static void main(String[] args) { String str="aabbbccdddddeee"; String result=removeRepeatChar(str); System.out.println(result); } public static String removeRepeatChar(String s) { if (s == null) { return ""; } StringBuffer sb = new StringBuffer(); int i = 0; int len = s.length(); while (i < len) { char c = s.charAt(i); sb.append(c); i++; while (i < len && s.charAt(i) == c) {//這個是如果這兩個值相等,就讓i+1取下一個元素 i++; } } return sb.toString(); } }
方法二
import java.util.ArrayList; import java.util.List; public class delchongfu { public static void main(String[] args) { String str = "asdadasfsasa"; List<String> data = new ArrayList<String>(); for (int i = 0; i < str.length(); i++) { String s = str.substring(i, i + 1); if (!data.contains(s)) { data.add(s); } } String result = ""; for (String s : data) { result += s; } System.out.println(result); } }
方法三 (HashSet法)
package zifuchuan; import java.util.HashSet; public class HashSetTest { public static HashSet<Character> hashsetTest(String aa) { HashSet<Character> newhash = new HashSet<>(); int i = 0; while(i<aa.length()) { char c = aa.charAt(i); newhash.add(c); i++; } return newhash; } public static void main(String[] args) { String str = "aabbccaabbcc"; HashSet<Character> newhash = hashsetTest(str); for(char cc : newhash) { System.out.print(cc); } }
對於陣列同理
public static void main(String[] args) {
int []a = {1,2,122,3,1,5,9,8,5,6};
HashSet set = new HashSet();
for (int i = 0 ; i < a.length; i++){
set.add(a[i]);
}
Iterator item = set.iterator();
while(item.hasNext()){
System.out.println(item.next());
}
}