TheQ TheQ - 21 days ago 5
Java Question

How to split a string in java at particular index?

so I have a method that takes in a string, and if its 3 elements then i put a

:
in between the 0th and 1st element. example -> "123" -> "1:23". And if its 4 elements then i put a
:
in between the first and and second element. "1234" -> "12:34" But for some reason I keep on getting odd results.

Here is my method

private String addColon(String openOrclose)
{
String newHour = null;
if(openOrclose.length() == 3)
{
newHour = openOrclose.substring(0,0) + ":" + openOrclose.substring(1,2);

}
else
{
newHour = openOrclose.substring(0,1) + ":" + openOrclose.substring(2,3);
}
return newHour;
}


For 3 elements my results show
:2
and for 4 elements my results are
1:3

Answer

You are close. You need to adjust the indicies for the substring calls:

private String addColon(String openOrclose)
{
    String newHour = null;
    if(openOrclose.length() == 3)
    {
        newHour = openOrclose.substring(0,1) + ":" + openOrclose.substring(1,3);

    }
    else
    {
        newHour = openOrclose.substring(0,2) + ":" + openOrclose.substring(2,4);
    }
    return newHour;
}