In java how to get substring from a string till a character c?

前端 未结 9 675
广开言路
广开言路 2020-12-04 16:26

I have a string (which is basically a file name following a naming convention) abc.def.ghi

I would like to extract the substring before the first

9条回答
  •  醉话见心
    2020-12-04 16:36

    The accepted answer is correct but it doesn't tell you how to use it. This is how you use indexOf and substring functions together.

    String filename = "abc.def.ghi";     // full file name
    int iend = filename.indexOf("."); //this finds the first occurrence of "." 
    //in string thus giving you the index of where it is in the string
    
    // Now iend can be -1, if lets say the string had no "." at all in it i.e. no "." is found. 
    //So check and account for it.
    
    String subString;
    if (iend != -1) 
    {
        subString= filename.substring(0 , iend); //this will give abc
    }
    

提交回复
热议问题