TheQ
TheQ

Reputation: 2019

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

I have a method that takes in a string.

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.

Upvotes: 0

Views: 4415

Answers (3)

Gulllie
Gulllie

Reputation: 558

The issue is the indexes that you're passing into substring():

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

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

Quoted from the Java Doc:

Returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex. Examples:

"hamburger".substring(4, 8) returns "urge" "smiles".substring(1, 5) returns "mile"

Upvotes: 0

JaysonP
JaysonP

Reputation: 149

Your issue seems very much related to this question Insert a character in a string at a certain position

Note: I would have just commented this under your question but I have 49 reputation and need 1 more point to do so.

Upvotes: 0

Michael Markidis
Michael Markidis

Reputation: 4191

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;
}

Upvotes: 4

Related Questions