Home > Java > javaTutorial > How to Correctly Split a Java String Using a Literal Dot (.)?

How to Correctly Split a Java String Using a Literal Dot (.)?

Mary-Kate Olsen
Release: 2024-11-23 13:32:09
Original
166 people have browsed it

How to Correctly Split a Java String Using a Literal Dot (.)?

Java String Split with "." (Dot)

The issue here is the ambiguous nature of the dot "." character in Java string splitting.

In the code provided, the line String extensionRemoved = filename.split(".")[0]; fails with an ArrayIndexOutOfBoundsException because the dot is interpreted as a wildcard character that matches any character, resulting in an empty array after splitting.

To split on a literal dot, it's necessary to escape it using \.:

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

This ensures that the dot is treated as a literal character rather than a wildcard.

Alternatively, you can use the overloaded version of split with a negative limit to disable the removal of trailing blanks from the result:

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

This will return a non-empty array even if filename is a single dot.

It's important to note that if filename contains multiple dots, the split method will return an array of strings divided by the dots. Therefore, it's essential to handle the number of elements returned from the split method to avoid any potential exceptions.

The above is the detailed content of How to Correctly Split a Java String Using a Literal Dot (.)?. 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