Skip to content

Commit a620f57

Browse files
authored
Merge pull request #16769 from sk1418/replace-last-occurrence
[replace-last-occurrence] replace last occurrence
2 parents 258cf42 + 771c134 commit a620f57

File tree

1 file changed

+36
-5
lines changed

1 file changed

+36
-5
lines changed

core-java-modules/core-java-string-algorithms-2/src/test/java/com/baeldung/replaceremove/StringReplaceAndRemoveUnitTest.java

Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,19 @@
11
package com.baeldung.replaceremove;
22

3-
import org.apache.commons.lang3.RegExUtils;
4-
import org.apache.commons.lang3.StringUtils;
5-
import org.junit.Test;
6-
73
import static org.junit.Assert.assertEquals;
84
import static org.junit.Assert.assertFalse;
95
import static org.junit.Assert.assertTrue;
106

7+
import org.apache.commons.lang3.RegExUtils;
8+
import org.apache.commons.lang3.StringUtils;
9+
import org.junit.Test;
10+
1111
public class StringReplaceAndRemoveUnitTest {
1212

1313
private static final String INPUT1 = "some prefix=Important Info: a=b";
1414
private static final String INPUT2 = "some prefix<a, <b, c>>";
15+
private static final String INPUT3 = "The first word, the second word, the last word should be replaced.";
16+
private static final String EXPECTED3 = "The first word, the second word, the last *WORD* should be replaced.";
1517

1618
@Test
1719
public void givenTestStrings_whenReplace_thenProcessedString() {
@@ -22,7 +24,6 @@ public void givenTestStrings_whenReplace_thenProcessedString() {
2224
String processed = master.replace(target, replacement);
2325
assertTrue(processed.contains(replacement));
2426
assertFalse(processed.contains(target));
25-
2627
}
2728

2829
@Test
@@ -124,4 +125,34 @@ public void givenTestStrings_whenUsingRegexReplaceAll_thenGetExpectedResult() {
124125

125126
}
126127

128+
private String reverseString(String input) {
129+
return new StringBuilder(input).reverse().toString();
130+
}
131+
132+
@Test
133+
public void givenTestStrings_whenReverseAndReplaceFirst_thenGetExpectedResult() {
134+
String theWord = "word";
135+
String replacement = "*WORD*";
136+
137+
String reversedInput = reverseString(INPUT3);
138+
String reversedTheWord = reverseString(theWord);
139+
String reversedReplacement = reverseString(replacement);
140+
String reversedResult = reversedInput.replaceFirst(reversedTheWord, reversedReplacement);
141+
142+
String result = reverseString(reversedResult);
143+
144+
assertEquals(EXPECTED3, result);
145+
}
146+
147+
@Test
148+
public void givenTestStrings_whenUsingLastIndexOf_thenGetExpectedResult() {
149+
String theWord = "word";
150+
String replacement = "*WORD*";
151+
152+
int index = INPUT3.lastIndexOf(theWord);
153+
String result = INPUT3.substring(0, index) + replacement + INPUT3.substring(index + theWord.length());
154+
155+
assertEquals(EXPECTED3, result);
156+
}
157+
127158
}

0 commit comments

Comments
 (0)