2

In this class I'm splitting variables on different delimiters(namely || and &&)

Here is my class:

public class Test {


    public static void main(String[] args) {
        String orStatement = "here||there";
        String andStatement = "here&&there";
        splitOr(orStatement);
        splitAnd(andStatement);
    }
    public static String[] splitOr(String stringvar){

        if(!stringvar.contains("||")){
            throw new IllegalArgumentException("Must contain a double pipe || to split into or statements");
        }
        String[] orArray = stringvar.split("||");
        for(int i=0;i<orArray.length;i++){
            System.out.println(orArray[i]);
        }
        return orArray;
    }

    public static String[] splitAnd(String stringvar){

        if(!stringvar.contains("&&")){
            throw new IllegalArgumentException("Must contain a double ampersand && to split into and statements");
        }
        String[] andArray = stringvar.split("&&");
        for(int i=0;i<andArray.length;i++){
            System.out.println(andArray[i]);
        }
        return andArray;
    }
}

And here is the result:

h
e
r
e
|
|
t
h
e
r
e
here
there

Why am I getting this weird ambitious splitting?

4

1 回答 1

5

这是因为split需要正则表达式,并且|在正则表达式中使用时具有特殊含义。您需要用斜杠转义管道(它本身需要在 Java 字符串中转义):

String[] orArray = stringvar.split("\\|\\|");
于 2013-06-29T18:27:29.480 回答