Skip to content

Commit fc3e674

Browse files
Neetika23Neetika Khandelwal
andauthored
BAEL-9063 (#18301)
* BAEL-9063 * BAEL-9063 --------- Co-authored-by: Neetika Khandelwal <[email protected]>
1 parent ad79c92 commit fc3e674

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.baeldung.substringoperations;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
class StringSlicingUnitTest {
8+
9+
@Test
10+
void givenString_whenExtract_thenOutputSubstring() {
11+
String s = "Hello, World!";
12+
assertEquals("Hello", s.substring(0, 5));
13+
assertEquals("World!", s.substring(7));
14+
}
15+
16+
@Test
17+
void givenString_whenNegativeIndexing_thenOutputSubstringEquivalent() {
18+
String s = "Hello, World!";
19+
assertEquals("World!", s.substring(s.length() - 6));
20+
}
21+
22+
@Test
23+
void givenString_whenStepSlicing_thenOutputSubstring() {
24+
String s = "Hello, World!";
25+
StringBuilder result = new StringBuilder();
26+
for (int i = 0; i < s.length(); i += 2) {
27+
result.append(s.charAt(i));
28+
}
29+
assertEquals("Hlo ol!", result.toString());
30+
}
31+
32+
@Test
33+
void givenString_whenReverseString_thenOutputString() {
34+
String s = "Hello, World!";
35+
String reversed = new StringBuilder(s).reverse()
36+
.toString();
37+
assertEquals("!dlroW ,olleH", reversed);
38+
}
39+
40+
@Test
41+
void testNegativeStepWithStartStop() {
42+
String s = "Hello, World!";
43+
StringBuilder result = new StringBuilder();
44+
for (int i = s.length() - 7; i < s.length() - 1; i += 2) {
45+
result.append(s.charAt(i));
46+
}
47+
assertEquals(" ol", result.toString());
48+
}
49+
}

0 commit comments

Comments
 (0)