Split string with dot as delimiter

Viewed 91230

I am wondering if I am going about splitting a string on a . the right way? My code is:

String[] fn = filename.split(".");
return fn[0];

I only need the first part of the string, that's why I return the first item. I ask because I noticed in the API that . means any character, so now I'm stuck.

13 Answers
String str="1.2.3";
String[] cats = str.split(Pattern.quote("."));

The solution that worked for me is the following

String[] fn = filename.split("[.]");

Note: Further care should be taken with this snippet, even after the dot is escaped!

If filename is just the string ".", then fn will still end up to be of 0 length and fn[0] will still throw an exception!

This is, because if the pattern matches at least once, then split will discard all trailing empty strings (thus also the one before the dot!) from the array, leaving an empty array to be returned.

Using ApacheCommons it's simplest:

File file = ...
FilenameUtils.getBaseName(file.getName());

Note, it also extracts a filename from full path.

Related