Split string with dot as delimiter

Dean picture Dean · Aug 2, 2010 · Viewed 76.1k times · Source

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.

Answer

Marimuthu Madasamy picture Marimuthu Madasamy · Aug 2, 2010

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