in Android, Java, Programming

Split String in Java

always remember:

public class StringSplit {
  public static void main(String args[]) throws Exception{
    String testString = "Real|How|To";
    // bad
    System.out.println(java.util.Arrays.toString(
        testString.split("|")
    ));
    // output : [, R, e, a, l, |, H, o, w, |, T, o]

    // good
    System.out.println(java.util.Arrays.toString(
      testString.split("\\|")
    ));
    // output : [Real, How, To]
  }
}

The special character needs to be escaped with a “\” but since “\” is also a special character in Java, you need to escape it again with another “\” !

Share