Split string with dot as delimiter

后端 未结 13 2516
死守一世寂寞
死守一世寂寞 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:09

    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.

提交回复
热议问题