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

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

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 . (ie a dot)

In java doc api, I can't seem to find a method in String which does that.
Am I missing something? How to do it?

ベストアンサー1

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
}

おすすめ記事