Skip to content

Commit 70ca471

Browse files
authored
Remove the last character of a Java StringBuilder (eugenp#12653)
1 parent b6cf7e7 commit 70ca471

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.baeldung.removelastcharfromsb;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
class RemoveLastCharFromSbUnitTest {
8+
@Test
9+
void givenSb_whenRemovingUsingDeleteCharAt_shouldGetExpectedResult() {
10+
StringBuilder sb = new StringBuilder("Using the sb.deleteCharAt() method!");
11+
sb.deleteCharAt(sb.length() - 1);
12+
assertEquals("Using the sb.deleteCharAt() method", sb.toString());
13+
}
14+
15+
@Test
16+
void givenSb_whenRemovingUsingReplace_shouldGetExpectedResult() {
17+
StringBuilder sb = new StringBuilder("Using the sb.replace() method!");
18+
int last = sb.length() - 1;
19+
sb.replace(last, last + 1, "");
20+
assertEquals("Using the sb.replace() method", sb.toString());
21+
}
22+
23+
@Test
24+
void givenSb_whenRemovingUsingSubString_shouldGetExpectedResult() {
25+
StringBuilder sb = new StringBuilder("Using the sb.substring() method!");
26+
assertEquals("Using the sb.substring() method", sb.substring(0, sb.length() - 1));
27+
//the stringBuilder object is not changed
28+
assertEquals("Using the sb.substring() method!", sb.toString());
29+
}
30+
}

0 commit comments

Comments
 (0)