From 70ca4712b29ef4cd5f0d96ee89f085315ccbe26c Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Sat, 27 Aug 2022 18:07:36 +0200 Subject: [PATCH] Remove the last character of a Java StringBuilder (#12653) --- .../RemoveLastCharFromSbUnitTest.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 core-java-modules/core-java-string-apis/src/test/java/com/baeldung/removelastcharfromsb/RemoveLastCharFromSbUnitTest.java diff --git a/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/removelastcharfromsb/RemoveLastCharFromSbUnitTest.java b/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/removelastcharfromsb/RemoveLastCharFromSbUnitTest.java new file mode 100644 index 0000000000..8c1a4306ea --- /dev/null +++ b/core-java-modules/core-java-string-apis/src/test/java/com/baeldung/removelastcharfromsb/RemoveLastCharFromSbUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.removelastcharfromsb; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +class RemoveLastCharFromSbUnitTest { + @Test + void givenSb_whenRemovingUsingDeleteCharAt_shouldGetExpectedResult() { + StringBuilder sb = new StringBuilder("Using the sb.deleteCharAt() method!"); + sb.deleteCharAt(sb.length() - 1); + assertEquals("Using the sb.deleteCharAt() method", sb.toString()); + } + + @Test + void givenSb_whenRemovingUsingReplace_shouldGetExpectedResult() { + StringBuilder sb = new StringBuilder("Using the sb.replace() method!"); + int last = sb.length() - 1; + sb.replace(last, last + 1, ""); + assertEquals("Using the sb.replace() method", sb.toString()); + } + + @Test + void givenSb_whenRemovingUsingSubString_shouldGetExpectedResult() { + StringBuilder sb = new StringBuilder("Using the sb.substring() method!"); + assertEquals("Using the sb.substring() method", sb.substring(0, sb.length() - 1)); + //the stringBuilder object is not changed + assertEquals("Using the sb.substring() method!", sb.toString()); + } +}