java去除反復的字符串和移除不想要的字符串


在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);




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM