Issue
What is the best way to replace the string/word between 2nd underscore and 3rd underscore?
This is my usual string X Services alba_tango_2021H1_[ten]
And I want to replace 2021H1
with test
.
X Services alba_tango_test_[ten]
I tried different ways but they don't work and I don't want to divide the string into different arrays, as I think is a very long way.
Solution
You can use indexOf and specify the fromIndex
parameter, this way you can easily find out the first, the second and the third occurrence of underscore. But just make sure that the assumption that your String
has 3 underscores is correct. In the example below:
input
is the index you want to work withreplacement
is whatever you want to place between the second and third underscoreoutput
is theString
you need
int firstUnderscore = input.indexOf("_");
int secondUnderscore = input.indexOf("_", firstUnderscore + 1);
int thirdUnderscore = input.indexOf("_", secondUnderscore + 1);
String output = input.substring(0, firstUnderscore + 1) + replacement + input.substring(thirdUnderscore);
EDIT
The code above assumes that we know for sure that there are at least 3 underscores. If there is any possibility that the String
would contain less than 3 underscores, then you will always need to check whether indexOf()
returns a value that's greater or equal than 0, which means that there was a valid index for the searched term, in other words, it means that the searched term was found.
In my answer I avoided this check because the question seemed to suggest that we have a format that we can rely on, so I decided to rely on this format rather than complicate the answer with indexOf
checks. If we cannot rely on this format, then we can change the code to something like
String output = input;
int firstUnderscore = input.indexOf("_");
if (firstUnderscore >= 0) {
int secondUnderscore = input.indexOf("_", firstUnderscore + 1);
if (secondUnderscore >= 0) {
int thirdUnderscore = input.indexOf("_", secondUnderscore + 1);
if (thirdUnderscore >= 0) output = input.substring(0, firstUnderscore + 1) + replacement + input.substring(thirdUnderscore);
}
}
Answered By - Lajos Arpad
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)