java中String类的split()方法详解

本文详细探讨了Java中String类的split()方法,解释了如何在给定正则表达式的基础上拆分字符串。内容包括split方法的重载形式,limit参数的作用,以及不同limit值对结果数组的影响。通过实例演示了limit为0、负数和正数时的匹配行为,揭示了在连续样板和结尾样板情况下的处理方式。
摘要由CSDN通过智能技术生成

split(String regex)为java.lang.String类的方法,其功能可简单描述为在给定正则表达式的匹配位置拆分该字符串。

该方法的具体定义为

public String[] split(String regex) {
   
    return split(regex, 0);
}

可以很明显地看到方法内部调用了一个重载的split(regex,0)方法,split(regex)方法最终返回一个字符串数组。
split(regex,0)的原型为split(String regex, int limit),该方法中的regex为匹配样板,而参数limit似乎不太好理解,通过查阅api文档得到如下说明

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array’s length will be no greater than n, and the array’s last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

翻译如下:

limit这个参数控制样板(pattern)应用的次数,因此它影响结果数组的长度。如果limit的值为n>0,那么样板会被应用n-1次,如此一来结果数组的长度就会不大于

  • 7
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值