Reputation: 2019
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
.
Upvotes: 0
Views: 4415
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
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
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