String.split

分割字符串碰到了一些疑问,在此整理一下。

1.使用特殊字符“.”或”|“分割时需要转译

1.不使用反斜杠转义,使用“.”进行分割没有结果

  /** * result: empty */
    public static void splitDotWithoutBackSlash() {
        String testString = "hello.world";
        String[] splitArray = testString.split(".");
        for (int i = 0; i < splitArray.length; i++) {
            String s = splitArray[i];
            System.out.print(" " + s);
        }
    }
   /** * result: hello world */
    public static void splitDotWithBackSlash() {
        String testString = "hello.world";
        final String[] splitArray = testString.split("\\.");
        for (int i = 0; i < splitArray.length; i++) {
            String s = splitArray[i];
            System.out.print(" " + s);
        }
    }

1.不使用反斜杠转义,使用“|”进行分割会可能会出现奇葩结果

/** * result: h e l l o | w o r l d */
    public static void splitDotWithoutBackSlash() {
        String testString = "hello|world";
        String[] splitArray = testString.split("|");
        for (int i = 0; i < splitArray.length; i++) {
            String s = splitArray[i];
            System.out.print(" " + s);
        }
    }

    /** * result: hello world */
    public static void splitDotWithBackSlash() {
        String testString = "hello|world";
        final String[] splitArray = testString.split("\\|");
        for (int i = 0; i < splitArray.length; i++) {
            String s = splitArray[i];
            System.out.print(" " + s);
        }
    }

2.最简单的分割样式

1.将所有符合条件的字符串都进行分解

  /** * result: * I * love * my * home */
    public static void splitBlank() {
        String testString = "I love my home";
        String[] splitArray = testString.split(" ");
        for (int i = 0; i < splitArray.length; i++) {
            String s = splitArray[i];
            System.out.println(" " + s);
        }
    }

2.限制分解的结果集的个数,最后一组会囊括剩余部分

 /** * result: * I * love * my home */
    public static void splitBlankLimitNum() {
        String testString = "I love my home";
        String[] splitArray = testString.split(" ", 3);
        for (int i = 0; i < splitArray.length; i++) {
            String s = splitArray[i];
            System.out.println(" " + s);
        }
    }

3.使用正则表达式,对字符串进行分割

   /** * result: I love my home */
    public static void splitRegular() {
        String testString = "I,love.my'home";
        String[] splitArray = testString.split("[^a-zA-Z0-9]");
        for (int i = 0; i < splitArray.length; i++) {
            String s = splitArray[i];
            System.out.print(" " + s);
        }
    }

参考地址

http://www.360doc.com/content/13/0728/19/13247663_303185497.shtml
http://juck.iteye.com/blog/1541247

你可能感兴趣的:(java,String,split)