2017-05-14 148 views
0
public class SplitTest { 
    public static void main(String[] args) { 
     String string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
     String[] strToSplit = new String[] { "GH", "MN" }; 
     for (String de : strToSplit) { 
      if (string.contains(de)) { 
       String[]str = string.split(de); 
       for (int i = 0; i < str.length; i++) { 
        System.out.println(str[i]); 
       } 
      } 
     } 
    } 
} 

輸出:如何通過Java中的多字符串分隔符分割字符串?

ABCDEF,IJKLMNOPQRSTUVWXYZ,ABCDEFGHIJKL,OPQRSTUVWXYZ 

,但實際產量:

ABCDEF,IJKL,OPQRSTUVWXYZ 
+4

[運行你的程序產生你期望的輸出](http://ideone.com/bmMxVv)。投票結束,不可重複。 – dasblinkenlight

回答

0

你可以不喜歡它通過在首位,而不是在第一個地方分割字符串獨特的分隔符來替換字符串的另一種方式。後來你可以通過獨特的分隔符來分割整個字符串。爲前。

public class SplitTest { 
public static void main(String[] args) { 
    String string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
    String str; 
    String[] strToSplit = new String[] { "GH", "MN" }; 
    for (String de : strToSplit) { 
     if (string.contains(de)) { 
      str = string.replace(de,unique_delimiter); 

     } 
    } 
    String [] finalString = str.split(unique_delimiter); 
    for (int i = 0; i < finalString.length; i++) { 
       System.out.println(finalString[i]); 
      } 
} 
} 

希望這會有所幫助。