From d1067b341fe8c7448ca4bf9148d121ba082c46bb Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Sun, 23 Oct 2022 16:50:15 +0200 Subject: [PATCH] [strToChar] Convert String to char in Java (#12893) --- .../ConvertStringToCharUnitTest.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/strtochar/ConvertStringToCharUnitTest.java diff --git a/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/strtochar/ConvertStringToCharUnitTest.java b/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/strtochar/ConvertStringToCharUnitTest.java new file mode 100644 index 0000000000..6de41b11dd --- /dev/null +++ b/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/strtochar/ConvertStringToCharUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.strtochar; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class ConvertStringToCharUnitTest { + private static final String STRING_b = "b"; + private static final String STRING_Baeldung = "Baeldung"; + + @Test + void givenStringWithSingleChar_whenCallingCharAt_thenGetExpectedResult() { + assertEquals('b', STRING_b.charAt(0)); + assertEquals('l', STRING_Baeldung.charAt(3)); + assertThrows(StringIndexOutOfBoundsException.class, () -> "".charAt(0)); + } + + @Test + void givenStringWithMultipleChars_whenCallingCharAt_thenGetExpectedResult() { + assertArrayEquals(new char[] { 'B', 'a', 'e', 'l', 'd', 'u', 'n', 'g' }, STRING_Baeldung.toCharArray()); + assertArrayEquals(new char[] {}, "".toCharArray()); + } + + @Test + void givenStringWithMultipleChars_whenCallingGetChars_thenGetExpectedResult() { + char[] aeld = new char[4]; + STRING_Baeldung.getChars(1, 5, aeld, 0); + assertArrayEquals(new char[] { 'a', 'e', 'l', 'd' }, aeld); + + char[] anotherArray = new char[] { '#', '#', '#', '#', '#', '#' }; + STRING_Baeldung.getChars(1, 5, anotherArray, 1); + assertArrayEquals(new char[] { '#', 'a', 'e', 'l', 'd', '#' }, anotherArray); + } +} \ No newline at end of file