Java 字符串用“."分割(点) [英] Java string split with "." (dot)

查看:38
本文介绍了Java 字符串用“."分割(点)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这段代码的第二行会抛出ArrayIndexOutOfBoundsException?

Why does the second line of this code throw ArrayIndexOutOfBoundsException?

String filename = "D:/some folder/001.docx";
String extensionRemoved = filename.split(".")[0];

虽然这有效:

String driveLetter = filename.split("/")[0];

我使用 Java 7.

I use Java 7.

推荐答案

如果要在文字点上拆分,则需要对点进行转义:

You need to escape the dot if you want to split on a literal dot:

String extensionRemoved = filename.split("\.")[0];

否则,您将在正则表达式 . 上拆分,这意味着任何字符".
请注意在正则表达式中创建单个反斜杠所需的双反斜杠.

Otherwise you are splitting on the regex ., which means "any character".
Note the double backslash needed to create a single backslash in the regex.

您得到一个 ArrayIndexOutOfBoundsException 因为您的输入字符串只是一个点,即 ".",这是一个边缘情况,在拆分时会产生一个空数组点;split(regex) 从结果中删除所有尾随空白,但由于在一个点上拆分一个点只留下两个空白,因此在删除尾随空白后,您会得到一个空数组.

You're getting an ArrayIndexOutOfBoundsException because your input string is just a dot, ie ".", which is an edge case that produces an empty array when split on dot; split(regex) removes all trailing blanks from the result, but since splitting a dot on a dot leaves only two blanks, after trailing blanks are removed you're left with an empty array.

为了避免在这种边缘情况下出现 ArrayIndexOutOfBoundsException,请使用 split(regex, limit),它有第二个参数是结果数组的大小限制.当 limitnegative 时,禁用从结果数组中删除尾随空白的行为:

To avoid getting an ArrayIndexOutOfBoundsException for this edge case, use the overloaded version of split(regex, limit), which has a second parameter that is the size limit for the resulting array. When limit is negative, the behaviour of removing trailing blanks from the resulting array is disabled:

".".split("\.", -1) // returns an array of two blanks, ie ["", ""]

即,当 filename 只是一个点 "." 时,调用 filename.split("\.", -1)[0] 将返回一个空白,但调用 filename.split("\.")[0] 将抛出一个 ArrayIndexOutOfBoundsException.

ie, when filename is just a dot ".", calling filename.split("\.", -1)[0] will return a blank, but calling filename.split("\.")[0] will throw an ArrayIndexOutOfBoundsException.

这篇关于Java 字符串用“."分割(点)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆