在java開發中碰到了有些字符串是重復的,如果在進行業務處理要全部遍歷太對的數據就會重復,所以在進行業務處理前進行一個去重操作。
這里由於業務需要所以先將字符串轉化為string數組,使用split分割,然后將string數組一個個放到list里(list的remove可以將你不要的字符串刪除掉,代參數的哦)
可以看到我使用的是list,在list里包含了一個contains函數,表示當前字符串是否與list里的元素有相同沒有就add進list里
在最后還將list里的元素轉化為string數組就將重復的字符串去除了,在最后使用了substring將字符串截取,在這里如果你的otherAppid太長的話會造成內存溢出,因為substring
的實現是先將字符串拷貝到另一塊內存,然后將字符串截取(這也是我看了支付寶的支付dom有個疑問然后查找資料得到的有興趣的可以找下資料看下)所以可以使用
int i=0;
if (i == newStr.length-1) {//拼接時,不包括最后一個,字符
otherAppid=otherAppid+commercial_account;
} else {
otherAppid=otherAppid+commercial_account+",";
}
i++;
判斷下。
貼出代碼
String otherAppid="";
String tmp="123,234,123,234,567,789,adb,asc,dcf,adb";
String[] commercial_accounts=tmp.split(",");
List<String> list = new ArrayList<String>();
for (int i=0; i<commercial_accounts.length; i++) {
System.out.print("commercial_accounts:"+commercial_accounts[i]);
System.out.print("\n");
if(!list.contains(commercial_accounts[i])){
//去除重復的字符串
list.add(commercial_accounts[i]);
}
}
//list.remove(1); 去除不想要的字符串
String[] newStr = list.toArray(new String[0]); //返回一個數組
int i = 0;
for(String commercial_account:newStr){
//otherAppid=otherAppid+commercial_account+",";
if (i == newStr.length-1) {//拼接時,不包括最后一個,字符
otherAppid=otherAppid+commercial_account;
} else {
otherAppid=otherAppid+commercial_account+",";
}
i++;
}
System.out.print("otherAppid:"+otherAppid);
System.out.print("\n");
//otherAppid=otherAppid.substring(0,otherAppid.length()-1);
System.out.print("otherAppid:"+otherAppid);