zoukankan      html  css  js  c++  java
  • ava中关于String的split(String regex, int limit) 方法

    https://www.cnblogs.com/zhang-cb/p/6112616.html

    今天在对一个String对象进行拆分的时候,总是无法到达预计的结果。呈现数据的时候出现异常,后来debug之后才发现,错误出在String spilt上,于是开始好好研究下这东西,开始对api里的split(String regex, int limit)比较感兴趣,可是就是不理解当limit为负数时的情况 
    下面是api里的解释:


    limit 参数控制模式应用的次数,因此影响所得数组的长度。如果该限制 n 大于 0,则模式将被最多应用 n - 1 次,数组的长度将不会大于 n,而且数组的最后一项将包含所有超出最后匹配的定界符的输入。如果 n 为非正,那么模式将被应用尽可能多的次数,而且数组可以是任何长度。如果 n 为 0,那么模式将被应用尽可能多的次数,数组可以是任何长度,并且结尾空字符串将被丢弃。

    例如,字符串 "boo:and:foo" 使用这些参数可生成以下结果:

    Regex Limit 结果

    : 2 { "boo", "and:foo" } 
    : 5 { "boo", "and", "foo" } 
    : -2 { "boo", "and", "foo" } 
    o 5 { "b", "", ":and:f", "", "" } 
    o -2 { "b", "", ":and:f", "", "" } 
    o 0 { "b", "", ":and:f" }


    对limit为负还是有点不理解,尤其是对 o -2组合,

    现在我明白了,{ "b", "", ":and:f", "", "" } 第一个“”是因为两个o之间的空数据,第二个也是这个原因,最后一个是将"boo:and:foo"中最后空字符串也算进去的。

    public String[] split(String regex, int limit)

    limit n 大于0,则pattern(模式)应用n - 1 次

    关于String.split(String regex, int limit)String s = “boo:and:foo” 
    关于String.split(String regex, int limit)s.split(“:”,2) 
    关于String.split(String regex, int limit)//result is { “boo”, “and:foo” } 
    limit n 小于0,则pattern(模式)应用无限次

    关于String.split(String regex, int limit)String s = “boo:and:foo” 
    关于String.split(String regex, int limit)s.split(“:”,-2) 
    关于String.split(String regex, int limit)//result is { “boo”, “and”, “foo” } 
    limit n 等于0,则pattern(模式)应用无限次并且省略末尾的空字串

    关于String.split(String regex, int limit)String s = “boo:and:foo” 
    关于String.split(String regex, int limit)s.split(“o”, -2) 
    //result is { “b”, “”, “and:f”, “”, “” } 
    s.split(“o”, 0) 
    //result is { “b”, “”, “and:f” }

    例子:string “boo:and:foo”

    Regex Limit Result
    2 { “boo”, “and:foo” }
    5 { “boo”, “and”, “foo” }
    -2 { “boo”, “and”, “foo” } 
    o 5 { “b”, “”, “:and:f”, “”, “” } 
    o -2 { “b”, “”, “:and:f”, “”, “” } 
    o 0 { “b”, “”, “:and:f” }
  • 相关阅读:
    C++入门经典-例3.4-根据成绩划分等级
    C++入门经典-例3.3-if-else语句的奇偶性判别
    C++入门经典-例3.2-根据分数判断是否优秀
    C++入门经典-例3.1-判断输入的数字是否为奇数
    C++入门经典-例2.17强制类型转换
    C++入门经典-例2.16-隐式类型转换
    C++入门经典-例2.15-逗号表达式的应用
    C++入门经典-例2.14-使用移位运算
    C++入门经典-例2.13-左移运算
    Spring之Bean管理------注解方式
  • 原文地址:https://www.cnblogs.com/manhuidhu/p/8031305.html
Copyright © 2011-2022 走看看