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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值