11package com .baeldung .replaceremove ;
22
3- import org .apache .commons .lang3 .RegExUtils ;
4- import org .apache .commons .lang3 .StringUtils ;
5- import org .junit .Test ;
6-
73import static org .junit .Assert .assertEquals ;
84import static org .junit .Assert .assertFalse ;
95import 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+
1111public 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