TheQ TheQ - 25 days ago 6
Java Question

How to split a string in Java at a particular index?

I have a method that takes in a string.


  • If it has three characters, then I put a
    :
    in between the zeroth and first element.
    Example:
    123
    1:23

  • If it has four characters, then I put a
    :
    in between the first and and second element.
    Example:
    1234
    12:34



For some reason, I keep 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 three characters, my result is
:2
, and for four characters, my result is
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;
}