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];
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.
Wouldn't it be more efficient to use
filename.substring(0, filename.indexOf("."))
if you only want what's up to the first dot?
Usually its NOT a good idea to unmask it by hand. There is a method in the Pattern class for this task:
java.util.regex
static String quote(String s)
The solution that worked for me is the following
filename.split("[.]");
split()
accepts a regular expression, so you need to escape .
to not consider it as a regex meta character. Here's an example :
String[] fn = filename.split("\\.");
return fn[0];
The split must be taking regex as a an argument... Simply change "."
to "\\."