点赞再看,动力无限。 微信搜「程序猿阿朗 」。

本文 Github.com/niumoo/JavaNotes未读代码博客 已经收录,有很多知识点和系列文章。

在日常的 Java 开发中,由于 JDK 未能提供足够的常用的操作类库,通常我们会引入 Apache Commons Lang 工具库或者 Google Guava 工具库简化开发过程。两个类库都为 java.lang API 提供了很多实用工具,比如经常使用的字符串操作,基本数值操作、时间操作、对象反射以及并发操作等。

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>

但是,最近在使用 Apache Commons Lang 工具库时踩了一个坑,导致程序出现了意料之外的结果。

StringUtils.split 的坑

也是因为踩了这个坑,索性写下一篇文章好好介绍下 Apache Commons Lang 工具库中字符串操作相关 API。

先说坑是什么,我们都知道 String 类中到的 split 方法可以分割字符串,比如字符串 aabbccdd 根据 bc 分割的结果应该是 aabcdd 才对,这样的结果也很容易验证。

String str = "aabbccdd";
for (String s : str.split("bc")) {
System.out.println(s);
}
// 结果
aab
cdd

可能是因为 String 类中的 split 方法的影响,我一直以为 StringUtils.split 的效果应该相同,但其实完全不同,可以试着分析下面的三个方法输出结果是什么,StringUtils 是 Commons Lang 类库中的字符串工具类。

 public static void testA() {
String str = "aabbccdd";
String[] resultArray = StringUtils.split(str, "bc");
for (String s : resultArray) {
System.out.println(s);
}
}

我对上面 testA 方法的预期是 aabcdd ,但是实际上这个方法的运行结果是:

// testA 输出
aa
dd

可以看到 bc 字母都不见了,只剩下了 ab,这是已经发现问题了,查看源码后发现 StringUtils.split 方法其实是按字符进行操作的,不会把分割字符串作为一个整体来看,返回的结果中不也会包含用于分割的字符。

验证代码:

public static void testB() {
String str = "abc";
String[] resultArray = StringUtils.split(str, "ac");
for (String s : resultArray) {
System.out.println(s);
}
}
// testB 输出
b
public static void testC() {
String str = "abcd";
String[] resultArray = StringUtils.split(str, "ac");
for (String s : resultArray) {
System.out.println(s);
}
}
// testC 输出
b
d

输出结果和预期的一致了。

StringUtils.split 源码分析

点开源码一眼看下去,发现在方法注释中就已经进行提示了:返回的字符串数组中不包含分隔符

The separator is not included in the returned String array. Adjacent separators are treated as one separator. For more control over the split use the StrTokenizer class....

继续追踪源码,可以看到最终 split 分割字符串时入参有四个。

private static String[] splitWorker(
final String str, // 原字符串
final String separatorChars, // 分隔符
final int max, // 分割后返回前多少个结果,-1 为所有
final boolean preserveAllTokens // 暂不关注
) {
}

根据分隔符的不同又分了三种情况。

1. 分隔符为 null

final int len = str.length();
if (len == 0) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
final List<String> list = new ArrayList<>();
int sizePlus1 = 1;
int i = 0;
int start = 0;
boolean match = false;
boolean lastMatch = false;
if (separatorChars == null) {
// Null separator means use whitespace
while (i < len) {
if (Character.isWhitespace(str.charAt(i))) {
if (match || preserveAllTokens) {
lastMatch = true;
if (sizePlus1++ == max) {
i = len;
lastMatch = false;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
lastMatch = false;
match = true;
i++;
}
}
// ...
if (match || preserveAllTokens && lastMatch) {
list.add(str.substring(start, i));
}

可以看到如果分隔符为 null ,是按照空白字符 Character.isWhitespace() 分割字符串的。分割的算法逻辑为:

a. 用于截取的开始下标置为 0 ,逐字符读取字符串。

b. 碰到分割的目标字符,把截取的开始下标到当前字符之前的字符串截取出来。

c. 然后用于截取的开始下标置为下一个字符,等到下一次使用。

d. 继续逐字符读取字符串、

2. 分隔符为单个字符

逻辑同上,只是判断逻辑 Character.isWhitespace() 变为了指定字符判断。

// Optimise 1 character case
final char sep = separatorChars.charAt(0);
while (i < len) {
if (str.charAt(i) == sep) { // 直接比较
...

3. 分隔符为字符串

总计逻辑同上,只是判断逻辑变为包含判断。

 // standard case
while (i < len) {
if (separatorChars.indexOf(str.charAt(i)) >= 0) { // 包含判断
if (match || preserveAllTokens) {

如何解决?

1. 使用 splitByWholeSeparator 方法。

我们想要的是按整个字符串分割,StringUtils 工具类中已经存在具体的实现了,使用 splitByWholeSeparator 方法。

String str = "aabbccdd";
String[] resultArray = StringUtils.splitByWholeSeparator(str, "bc");
for (String s : resultArray) {
System.out.println(s);
}
// 输出
aab
cdd

2. 使用 Google Guava 工具库

关于 Guava 工具库的使用,之前也写过一篇文章,可以参考:Guava - 拯救垃圾代码

String str = "aabbccdd";
Iterable<String> iterable = Splitter.on("bc")
.omitEmptyStrings() // 忽略空值
.trimResults() // 过滤结果中的空白
.split(str);
iterable.forEach(System.out::println);
// 输出
aab
cdd

3. JDK String.split 方法

使用 String 中的 split 方法可以实现想要效果。

String str = "aabbccdd";
String[] res = str.split("bc");
for (String re : res) {
System.out.println(re);
}
// 输出
aab
cdd

但是 String 的 split 方法也有一些坑,比如下面的输出结果。

String str = ",a,,b,";
String[] splitArr = str.split(",");
Arrays.stream(splitArr).forEach(System.out::println);
// 输出 a b

开头的逗号,前出现了空格,末尾的逗号,后却没有空格。

一如既往,文章中代码存放在 Github.com/niumoo/javaNotes.

<完>

文章持续更新,可以微信搜一搜「 程序猿阿朗 」或访问「程序猿阿朗博客 」第一时间阅读。本文 Github.com/niumoo/JavaNotes 已经收录,有很多知识点和系列文章,欢迎Star。

使用 StringUtils.split 的坑的更多相关文章

  1. String.split()与StringUtils.split()

    我们平时进行简单的字符串分割的时候,尽量不要用String自身的split方法,它是匹配正则表达式的,如果遇到$这种特殊字符,需要转义一下.用StringUtils.split()方法会更方便 使用a ...

  2. StringUtils.split()和string.split()的区别

    场景 出于业务考虑,将多个字符串拼接起来时,使用的分隔符是;,;.如果要将这样一个拼接来的字符串分割成原本的多个字符串时,就需要使用到jdk自带的split()方法.不过因为公司的编程规范,改为使用了 ...

  3. String.split()与StringUtils.split()的区别

    import com.sun.deploy.util.StringUtils; String s =",1,,2,3,4,,"; String[] split1 = s.split ...

  4. java的split的坑,会忽略空值

    String test = "@@@@"; String[] arrayTest = test.split("\\@"); System.out.println ...

  5. python2和python3中split的坑

    执行同样的split,python2和python3截取的行数内容却不一样 我想要截取Dalvik Heap行,使用split('\n')的方法 import os cpu='adb shell du ...

  6. java 字符串split有很多坑,使用时请小心!!

    System.out.println(":ab:cd:ef::".split(":").length);//末尾分隔符全部忽略 System.out.print ...

  7. JAVA StringUtils 坑汇总

    1 StringUtils.split() VS String.split(); public static void main(String args[]){            String r ...

  8. Mac下hadoop运行word count的坑

    Mac下hadoop运行word count的坑 Word count体现了Map Reduce的经典思想,是分布式计算中中的hello world.然而博主很幸运地遇到了Mac下特有的问题Mkdir ...

  9. JAVA踩坑录

    以前踩了很多坑,大多忘了.现在踩了坑,想起了一定记下来. 1. 字符串分割,这种工具类,首次使用一定要先看一眼,不然跳坑 commons-lang StringUtils.split分割时会去掉空串: ...

随机推荐

  1. 介绍下Java内存区域(运行时数据区)

    介绍下Java内存区域(运行时数据区) Java 虚拟机在执行 Java 程序的过程中会把它管理的内存划分成若干个不同的数据区域.JDK 1.8 和之前的版本略有不同. 下图是 JDK 1.8 对JV ...

  2. Sirni题解(最小生成树,埃氏筛)(继 Liang-梁)

    目录 前言 题意 思路 一些建议 前言 本篇是对Liang-梁的Sirni(最小生成树,埃氏筛)的后继博客. 通篇原文:https://blog.csdn.net/qq_37555704/articl ...

  3. MQ系列4:NameServer 原理解析

    MQ系列1:消息中间件执行原理 MQ系列2:消息中间件的技术选型 MQ系列3:RocketMQ 架构分析 1 关于NameServer 上一节的 MQ系列3:RocketMQ 架构分析,我们大致介绍了 ...

  4. Dynamic CRM插件中记录日志-Nlog记录到文本

    Dynamic CRM插件中记录日志的方式有多种 通常情况下分为ITracingService记录.单独日志表插入记录.文本记录三种. 之前整理过ITracingService记录的方式,但这种记录有 ...

  5. FR801xH开发

    一.空间分配 二.代码流程 1)user_custom_parameters 函数 __jump_table 结构体中保存了一些配置信息: void user_custom_parameters(vo ...

  6. 关于Ubuntu系统无法输入中文的问题,即使做了种种修改

    原网址:https://shurufa.sogou.com/linux/guide 在经历一晚上一及一下午的奋战后,找到了最终解决方案,该解决方案使用的是搜狗输入法 在操作之前有以下注意事项:所有操作 ...

  7. linux下搭建ftp文件服务器

    linux下搭建ftp文件服务器 一.搭建步骤(以在centos7中搭建为例) 1.首先检查一下系统中是否已经安装了vsftpd软件 # 查看是否安装vsftpd rpm -q vsftpd rpm ...

  8. typora收费了,最后一个免费版提供下载

    typora收费了,在这里,博主提供最后一个免费版下载,地址如下,顺便把typora导入和导出word时需要的工具也一同提供.最看不惯免费用着别人的软件,还搞引流的垃圾网站和公众号.地址如下 http ...

  9. 绕过CDN获取服务器真实IP地址

    相关视频链接:(https://blog.sechelper.com/20220914/penetration-testing-guide/cdn-bypass) CDN(Content Delive ...

  10. 第一个HTML

    第一个HTML <!DOCTYPE html><!--html 文件开始--><html lang="en"><!--head 文件头-- ...