Home > Java > javaTutorial > body text

Java String Splitting: Why Does `split(\'.\')` Throw an `ArrayIndexOutOfBoundsException`?

Mary-Kate Olsen
Release: 2024-11-24 21:12:12
Original
860 people have browsed it

Java String Splitting: Why Does `split(

Java String Split with ""." (Dot)

Problem:

Why does the following code throw an ArrayIndexOutOfBoundsException when attempting to split on a dot, but works when splitting on a slash:

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

versus:

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

Solution:

To split on a literal dot, the dot character must be escaped to avoid treating it as a regex pattern (any character):

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

The double backslash (\) is necessary to create a single backslash in the regex string.

Additionally, an edge case occurs when the input string is just a dot (".") because splitting it on a dot results in an empty array. To prevent an ArrayIndexOutOfBoundsException in this case, use the overloaded split(regex, limit) method with a negative limit to disable the removal of trailing blanks:

String extensionRemoved = filename.split("\.", -1)[0];
Copy after login

The above is the detailed content of Java String Splitting: Why Does `split(\'.\')` Throw an `ArrayIndexOutOfBoundsException`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template