String newDate = date.replace(date.subString(date.indexOf("-")+1,date.lastIndexOf("-")),"October");
Let's unwrap this. You are implicitly
int firstHyphen = date.indexOf("-");
int lastHyphen = date.lastIndexOf("-");
But for the given string, this is the same as saying
int firstHyphen = 2;
int lastHyphen = 5;
Next, you have an implicit variable creation
String month = date.subString(firstHyphen+1, lastHyphen);
Which is the same as
String month = date.subString(3, 5);
But what substring starts at 3 and ends before 5?
String month = "10";
So we can take your original code and replace it with
String newDate = date.replace("10", "October");
It should be clear now that you are NOT restricting to just that portion of the string between the hyphens. That restriction only applied to the substring. Once you use the result of the substring in the replace, you are just passing it a string. In particular, you are passing "10"
, which appears twice in the string, so it replaces it twice.
If you want to try to make this work, you could change your original code to look like
String newDate = date.replace(date.subString(date.indexOf("-"), date.lastIndexOf("-")), "-October");
This would replace "-10"
with "-October"
. As "-10"
only occurs in the string once, it will only do one replacement.
If you have a Map
that maps the integer months to the names, you might use it like
Map<String, String> months = new HashMap<>();
months.put("10", "October");
String month = date.subString(date.indexOf("-"), date.lastIndexOf("-"));
String newDate = date.replace(month, "-" + months.get(month.subString(1)));
This builds the "-October"
on the fly and will work for the other months, assuming that you populate the map with them. But as others have noted, it may be more reliable to use Java's built-in date parsing and formatting instead.