2015-02-08 26 views
0

我有適用於此的代碼。但在我看來,這是非常令人厭惡的,需要清理。從ArrayList中的字符串中刪除子串並放回列表中 - Java

問題出在這裏: 我有一個ArrayList,裏面有文件名,我試着迭代ArrayList並刪除文件名的結尾。

實施例:

ArrayList<String> files包含[am.sunrise.ios.png[email protected][email protected]am.sunrise.ios~ipad.png[email protected]]

爲了除去該串中的結束部件我目前執行以下操作:

private static ArrayList<String> removeTrailingElements(ArrayList<String> IBImages) { 
    for (int image = 0; image < IBImages.size(); image++) { 
     if (IBImages.get(image).endsWith("~ipad.png")) 
      IBImages.set(image, IBImages.get(image).substring(0, IBImages.get(image).indexOf("~ipad.png"))); 
     if (IBImages.get(image).endsWith("[email protected]")) 
      IBImages.set(image, IBImages.get(image).substring(0, IBImages.get(image).indexOf("[email protected]"))); 
     if (IBImages.get(image).endsWith("@2x~ipad.png")) 
      IBImages.set(image, IBImages.get(image).substring(0, IBImages.get(image).indexOf("@2x~ipad.png"))); 
     if (IBImages.get(image).endsWith("@2x.png")) 
      IBImages.set(image, IBImages.get(image).substring(0, IBImages.get(image).indexOf("@2x.png"))); 
     if (IBImages.get(image).endsWith("@3x.png")) 
      IBImages.set(image, IBImages.get(image).substring(0, IBImages.get(image).indexOf("@3x.png"))); 
     if (IBImages.get(image).endsWith(".png")) 
      IBImages.set(image, IBImages.get(image).substring(0, IBImages.get(image).indexOf(".png"))); 
    } 
    return IBImages; 
} 

顯然是一些可怕的代碼。我正在查看是否有人有一種更簡潔的方式來獲得由此產生的ArrayList以包含[am.sunrise.ios,am.sunrise.ios,am.sunrise.ios,am.sunrise.ios,am.sunrise.ios]。我打算將ArrayList轉換爲Set(我相信Java有這種功能,對於Java來說仍然是新功能),然後轉換回去以清除列表中的重複項,很像您在Python中執行的操作。

編輯: 在任何人來尋找這樣的解決方案的情況下,我發現了一個班輪,爲我工作(for循環中的一個班輪)。它和上面做的一樣,甚至把它放回到ArrayList中。

private static ArrayList<String> removeTrailingElements(ArrayList<String> IBImages) { 
    for (int image = 0; image < IBImages.size(); image++) { 
     IBImages.set(image, IBImages.get(image).split("~")[0].split("@")[0].split(".png")[0]); 
    } 
    return IBImages; 
} 
+0

什麼是切除的準確標準? 'ios'之後的任何內容? – 2015-02-08 01:54:19

回答

0

如果你有,你想手頭驅除掉文件名結尾的有限列表(如在你的榜樣「〜ipad.png」,「@ 3x.png」等)我建議你從他們構造一個正則表達式(例如,包括「〜」,「@」),然後做一個String.split(regex)。這會給你一個String[](字符串數組),其索引0上的值將是你之後的字符串。

或者,如果您希望擺脫字符串的某個部分(例如「ios」)後的所有內容,則可以執行String.split("ios")。要將「ios」部分返回到結果中,可以簡單地連接:String.split("ios")[0] + "ios"

+0

謝謝!我用你的建議,並找到一個單線解決方案!我感謝幫助! – tbcrawford 2015-02-08 18:22:21