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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-24 21:12:12933browse

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];

versus:

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

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];

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];

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!

Statement:
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