简体   繁体   English

如何在Java中使用多字符串定界符分割字符串?

[英]How do I split a string by a multiple-string delimiter in Java?

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]);
                }
            }
        }
    }
}

Output : 输出:

ABCDEF,IJKLMNOPQRSTUVWXYZ,ABCDEFGHIJKL,OPQRSTUVWXYZ

but actual output is : 但实际输出是:

ABCDEF,IJKL,OPQRSTUVWXYZ

You can do it another way like replace string by unique delimiter at first place instead of splitting string at first place .Later you can split whole string by unique delimiter. 您可以使用另一种方式,例如首先用唯一的分隔符替换字符串,而不是首先分割字符串。以后您可以用唯一的分隔符分割整个字符串。 for ex. 对于前。

 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]);
            }
}
}

Hope this would help. 希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM