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 ...
随机推荐
- AtCoder Regular Contest 080 [CDEF]
C - 4-adjacent Time limit : 2sec / Memory limit : 256MB Problem Statement We have a sequence of leng ...
- Django REST framework API开发
RESTful设计方法 1. 域名 应该尽量将API部署在专用域名之下. https://api.example.com 如果确定API很简单,不会有进一步扩展,可以考虑放在主域名下. https:/ ...
- 小甲鱼Python第十四课后习题
字符串格式化符号含义 符 号 说 明 %c 格式化字符及其ASCII码[>>> '%c' %97 'a'] %s ...
- Vue(十一)计算属性
计算属性 1. 基本用法 计算属性也是用来存储数据,但具有以下几个特点: a.数据可以进行逻辑处理操作 b.对计算属性中的数据进行监视 2.计算属性 vs 方法 将计算属性的get函数定义为一个方法也 ...
- JSP(7)—EL和JSTL
一.EL表达式: 1.简介:EL全称为Expression Language,原本是JSTL1.0为方便存储数据所定义的语言,当时只能在JSTL标签中 使用,到了JSTL2.0之后,EL已经成为正式纳 ...
- Wireshark抓包实例诊断TCP连接问题
转载请在文首保留原文出处:EMC中文支持论坛https://community.emc.com/go/chinese 介绍 前文论述了TCP基础知识,从本节开始,通过TCP抓包实例来诊断TCP常见问 ...
- django-关于manage.py migrate无效的问题
django-关于manage.py migrate无效的问题 2017年03月04日 15:23:36 Jessie-via 阅读数:12317 标签: pythondjango 更多 个人分类: ...
- 科技论文之Latex公式&符号
近期在写文章.有好多数学公式的命令都忘记了. 今天索性一起整理下. 1 能够在文章的作者上引用的符号 2 一些括号使用方法 3 一些高等数学的公式 4 交,并集 5 一些二项式 6 矩阵写法 7 ...
- debian linux sudo 无法执行以添加普通用户到sudo
安装debian时,默认创建了root用户,和一个普通用户: 用普通用户登录电脑,无法执行sudo命令: 查看 /etc/sudoers 无此文件: 那么说明,本机没有安装sudo 解决方式: 终端 ...
- Linux 互斥锁
互斥的概念 在多线程编程中,引入了对象互斥锁的概念,来保证共享数据操作的完整性. 每个对象都对应于一个可称为" 互斥锁" 的标记,这个标记用来保证在任一时刻, 只能有一个线程访问该 ...