java基础---->String中的split方法的原理
这里面主要介绍一下关于String类中的split方法的使用以及原理。
split函数的说明
split函数java docs的说明:
When there is a positive-width match at the beginning of this string then an empty leading substring is included at the beginning of the resulting array.A zero-width match at the beginning however never produces such empty leading substring. 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 - 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.
split函数的工作原理大概可以分为以下的几步:
、遍历查找到regex,把regex前面到上一次的位置中间部分添加到list。这是split函数的核心部分
、如果没有找到,则返回自身的一维数组
、是否添加剩余的内容到list中
、是否去除list里面的空字符串
、从上面的list里面返回成数组
对于split函数limit的值可能会出现以下的几种情况:
、Limit < , e.g. limit = -
、limit = ,不传默认是0
、Limit > ,e.g. limit =
、limit > size,e.g. limit =
split函数的原理
我们通过以下的例子来分析一下split函数的原理。
public void test() {
String string = "linux---abc-linux-";
splitStringWithLimit(string, -);
splitStringWithLimit(string, );
splitStringWithLimit(string, );
splitStringWithLimit(string, );
}
public void splitStringWithLimit(String string, int limit) {
String[] arrays = string.split("-", limit);
String result = MessageFormat.format("arrays={0}, length={1}", Arrays.toString(arrays), arrays.length);
System.out.println(result);
}
// arrays=[linux, , , abc, linux, ], length=6
// arrays=[linux, , , abc, linux], length=5
// arrays=[linux, , -abc-linux-], length=3
// arrays=[linux, , , abc, linux, ], length=6
一、关于第一步的操作,分为两个分支。
if (((regex.value.length == &&
".$|()[{^?*+\\".indexOf(ch = regex.charAt()) == -) ||
(regex.length() == &&
regex.charAt() == '\\' &&
(((ch = regex.charAt())-'')|(''-ch)) < &&
((ch-'a')|('z'-ch)) < &&
((ch-'A')|('Z'-ch)) < )) &&
(ch < Character.MIN_HIGH_SURROGATE ||
ch > Character.MAX_LOW_SURROGATE))
{
int off = ;
int next = ;
boolean limited = limit > ;
ArrayList<String> list = new ArrayList<>();
while ((next = indexOf(ch, off)) != -) {
if (!limited || list.size() < limit - ) {
list.add(substring(off, next));
off = next + ;
} else { // last one
//assert (list.size() == limit - 1);
list.add(substring(off, value.length));
off = value.length;
break;
}
}
// If no match was found, return this
if (off == )
return new String[]{this};
// Add remaining segment
if (!limited || list.size() < limit)
list.add(substring(off, value.length));
// Construct result
int resultSize = list.size();
if (limit == ) {
while (resultSize > && list.get(resultSize - ).length() == ) {
resultSize--;
}
}
String[] result = new String[resultSize];
return list.subList(, resultSize).toArray(result);
}
return Pattern.compile(regex).split(this, limit);
使用正则表达式的mather函数,查找到regex的位置。维护着index变量,相当于上述的off。而matcher查找到的m.start()则相当于上述的next。每次查找之后把index到m.start()中间的内容添加到list中。最后更新off的值为m.end()。以供下一次的查找。
public String[] split(CharSequence input, int limit) {
int index = ;
boolean matchLimited = limit > ;
ArrayList<String> matchList = new ArrayList<>();
Matcher m = matcher(input);
// Add segments before each match found
while(m.find()) {
if (!matchLimited || matchList.size() < limit - ) {
if (index == && index == m.start() && m.start() == m.end()) {
// no empty leading substring included for zero-width match
// at the beginning of the input char sequence.
continue;
}
String match = input.subSequence(index, m.start()).toString();
matchList.add(match);
index = m.end();
} else if (matchList.size() == limit - ) { // last one
String match = input.subSequence(index,
input.length()).toString();
matchList.add(match);
index = m.end();
}
}
// If no match was found, return this
if (index == )
return new String[] {input.toString()};
// Add remaining segment
if (!matchLimited || matchList.size() < limit)
matchList.add(input.subSequence(index, input.length()).toString());
// Construct result
int resultSize = matchList.size();
if (limit == )
while (resultSize > && matchList.get(resultSize-).equals(""))
resultSize--;
String[] result = new String[resultSize];
return matchList.subList(, resultSize).toArray(result);
}
二、关于第二步:
三、关于第三步:
四、关于第四步
五、关于第五步
友情链接
java基础---->String中的split方法的原理的更多相关文章
- java基础---->String中replace和replaceAll方法
这里面我们分析一下replace与replaceAll方法的差异以及原理. replace各个方法的定义 一.replaceFirst方法 public String replaceFirst(Str ...
- java.lang.String中的replace方法到底替换了一个还是全部替换了。
你没有看错我说的就是那个最常用的java.lang.String,String可以说在Java中使用量最广泛的类了. 但是我却发现我弄错了他的一个API(也可以说是两个API),这个API是关于字符串 ...
- Java的String中的subString()方法
方法如下: public String substring(int beginIndex, int endIndex) 第一个int为开始的索引,对应String数字中的开始位置, 第二个是截止的索引 ...
- java.lang.String中的trim()方法的详细说明(转)
String.Trim()方法到底为我们做了什么,仅仅是去除字符串两端的空格吗? 一直以为Trim()方法就是把字符串两端的空格字符给删去,其实我错了,而且错的比较离谱. 首先我直接反编译String ...
- PL/SQL实现JAVA中的split()方法的小例子
众所周知,java中为String类提供了split()字符串分割的方法,所以很容易将字符串以指定的符号分割为一个字符串数组.但是在pl/sql中并没有提供像java中的split()方法,所以要想在 ...
- Java基础String的方法
Java基础String的方法 字符串类型写法格式如下: 格式一: String 变量名称; 变量名称=赋值(自定义或传入的变量值); 格式二: String 变量名称=赋值(自定义或传入的变量值); ...
- java.lang.String 类的所有方法
java.lang.String 类的所有方法 方法摘要 char charAt(int index) 返回指定索引处的 char 值. int codePointAt(int index) 返回指定 ...
- 2017.10.28 针对Java Web应用中错误异常处理方法的运用
针对Java Web应用中错误异常处理方法的运用 在javaweb中其异常都需要对Checked Exception之下的Exception进行继承,并且有选择地对发生的错误和异常进行处理.Java同 ...
- Java基础关于Map(字典)的方法使用
Java基础关于Map(字典)的方法使用 java中一般用map与hashmap来创建一个key-value对象 使用前提是要导入方法包: import java.util.HashMap: impo ...
随机推荐
- jmeter接口测试实例1-添加学生信息
jmeter实例1:添加学生信息 进入jmeter,添加线程组改名称为添加学生信息(为了好区分接口),添加http请求,输入IP,方法,路径,在body data中输入json串,同上面postman ...
- win10电脑录教学视频的时候有回声或者通话的时候有回声,严重干扰录制效果,解决方式。
1.右键点击屏幕右下脚的小喇叭图标. 2.选择声音. 3.选择“录制”,出现如下 4.选择侦听 5.把侦听此设备 的打勾去掉.然后点击应用,点击确定,即可. 再也没有回声的烦恼了.
- jquery 上下滚动显示隐藏
function scroll(fn) { var beforeScrollTop = document.body.scrollTop, fn = fn || function() {}; win ...
- openstack 之~keystone部署
第一:版本信息 官网http://docs.openstack.org/newton/install-guide-rdo/keystone.html 我们按照Newton这个版本来部署,opensta ...
- Deepin 15.4 编译安装 LNMP(PHP 5.6.31 + Nginx 1.12.1 + MySQL 5.6.36)
先查看先前的文章:Ubuntu 14 编译安装 PHP 5.4.45 + Nginx 1.4.7 + MySQL 5.6.26 笔记 编译 Nginx #安装依赖库 sudo apt-get -y i ...
- 基于Token的身份认证 与 基于服务器的身份认证
基于Token的身份认证 与 基于服务器的身份认证 基于服务器的身份认证 在讨论基于Token的身份认证是如何工作的以及它的好处之前,我们先来看一下以前我们是怎么做的: HTTP协议是无状态的,也就是 ...
- webview 向右滑动关闭时,怎么禁止此 webview 上下滚动?
webview 向右滑动关闭时,怎么禁止此 webview 上下滚动?
- java-算法-排列组合
package com.qinghuainvest.utils.algorithm; import java.util.ArrayList; import java.util.Arrays; impo ...
- Win10系统的SurfacePro4无法修改启动顺序怎么办
必须要把底部的开关关闭,否则启动顺序无法修改
- VTK使用矢量数据弯曲几何体
vtkWarpVector is a filter that modifies point coordinates by moving points along vector times the sc ...