Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to substring a string to the second dot (.) in Java?

I have a String which has many segments separated by a dot (.) like this:

codes.FIFA.buf.OT.1207.2206.idu


I want to get a substring only until second dot, like codes.FIFA.

How to substring just until the second dot?

like image 387
itro Avatar asked Nov 27 '22 17:11

itro


2 Answers

Just find the first dot, then from there the second one:

String input = "codes.FIFA.buf.OT.1207.2206.idu";
int dot1 = input.indexOf(".");
int dot2 = input.indexOf(".", dot1 + 1);
String substr = input.substring(0, dot2);

Of course, you may want to add error checking in there, if dots are not found.

like image 177
Aleks G Avatar answered Dec 05 '22 03:12

Aleks G


Something like this will do the trick:

String[] yourArray = yourDotString.split(".");
String firstTwoSubstrings = yourArray[0] + "." + yourArray[1];

The variable firstTwoSubstrings will contain everything before the second ".". Beware that this will cause an exception if there are less than two "." in your string.

Hope this helps!

like image 31
Logard Avatar answered Dec 05 '22 02:12

Logard