1. 程式人生 > 實用技巧 >split函式(去重、去除空格)

split函式(去重、去除空格)

題目描述:實現split函式,去掉字串陣列中每一個字串前後空格並去除重複的字串

實現:

public class Test {
    public static List<String> split(String txt){
        String[] split = txt.split(",");
        Set<String> stringSet=new HashSet<>();
        List<String> stringList=new ArrayList<>();
        for (String string
: split) { String strReplace=""; if (string.startsWith(" ")||string.endsWith(" ")){ strReplace= string.replace(" ",""); }else { strReplace=string; } stringSet.add(strReplace); } for (String string
: stringSet) { stringList.add(string); } return stringList; } public static void main(String[] args) { String string="a, bb , c, a ,dd ,c c,bb"; List<String> split = Test.split(string); System.out.println(split); } }
  • 先調動字串的split函式,將字串進行分割,分割後的字串前後存在空格,且存在重複的字串
  • 呼叫字串的方法判斷字串前後是否存在空格,存在的話呼叫字串的replace方法,將字串中的空格替換掉,此時的字串前後已經沒有空格了
  • 將前後已經沒有空格的字串儲存到Set集合中進行去重,然後遍歷Set集合並將資料儲存到List集合中,因為函式的返回值是List集合