Split string with dot as delimiter

后端 未结 13 2457
死守一世寂寞
死守一世寂寞 2020-11-22 11:14

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


        
13条回答
  •  遥遥无期
    2020-11-22 12:07

    Split uses regular expressions, where '.' is a special character meaning anything. You need to escape it if you actually want it to match the '.' character:

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

    (one '\' to escape the '.' in the regular expression, and the other to escape the first one in the Java string)

    Also I wouldn't suggest returning fn[0] since if you have a file named something.blabla.txt, which is a valid name you won't be returning the actual file name. Instead I think it's better if you use:

    int idx = filename.lastIndexOf('.');
    return filename.subString(0, idx);
    

提交回复
热议问题