diff --git a/java-strings/src/main/java/com/baeldung/string/ReplaceCharacterInString.java b/java-strings/src/main/java/com/baeldung/string/ReplaceCharacterInString.java index e8d1ce2d8b..2cc67f0b51 100644 --- a/java-strings/src/main/java/com/baeldung/string/ReplaceCharacterInString.java +++ b/java-strings/src/main/java/com/baeldung/string/ReplaceCharacterInString.java @@ -1,12 +1,20 @@ package com.baeldung.string; public class ReplaceCharacterInString { - public String replaceCharSubstring(String str, char ch, int index) { - String myString = str.substring(0, index) + ch + str.substring(index+1); + + public String replaceCharSubstring(String str, char ch, int index) { + String myString = str.substring(0, index) + ch + str.substring(index + 1); return myString; } - public String replaceCharStringBuilder(String str, char ch, int index) { + public String replaceCharUsingCharArray(String str, char ch, int index) { + char[] chars = str.toCharArray(); + chars[index] = ch; + return String.valueOf(chars); + } + + + public String replaceCharStringBuilder(String str, char ch, int index) { StringBuilder myString = new StringBuilder(str); myString.setCharAt(index, ch); return myString.toString(); diff --git a/java-strings/src/test/java/com/baeldung/string/ReplaceCharInStringUnitTest.java b/java-strings/src/test/java/com/baeldung/string/ReplaceCharInStringUnitTest.java index 07e86bb69b..c234c6953c 100644 --- a/java-strings/src/test/java/com/baeldung/string/ReplaceCharInStringUnitTest.java +++ b/java-strings/src/test/java/com/baeldung/string/ReplaceCharInStringUnitTest.java @@ -1,23 +1,29 @@ package com.baeldung.string; import org.junit.Test; + import static org.junit.Assert.*; public class ReplaceCharInStringUnitTest { private ReplaceCharacterInString characterInString = new ReplaceCharacterInString(); @Test - public void whenReplaceCharAtIndexUsingSubstring_thenSuccess(){ - assertEquals("abcme",characterInString.replaceCharSubstring("abcde",'m',3)); + public void whenReplaceCharAtIndexUsingSubstring_thenSuccess() { + assertEquals("abcme", characterInString.replaceCharSubstring("abcde", 'm', 3)); } @Test - public void whenReplaceCharAtIndexUsingStringBuilder_thenSuccess(){ - assertEquals("abcme",characterInString.replaceCharStringBuilder("abcde",'m',3)); + public void whenReplaceCharAtIndexUsingCharArray_thenSuccess() { + assertEquals("abcme", characterInString.replaceCharUsingCharArray("abcde", 'm', 3)); } @Test - public void whenReplaceCharAtIndexUsingStringBuffer_thenSuccess(){ - assertEquals("abcme",characterInString.replaceCharStringBuffer("abcde",'m',3)); + public void whenReplaceCharAtIndexUsingStringBuilder_thenSuccess() { + assertEquals("abcme", characterInString.replaceCharStringBuilder("abcde", 'm', 3)); + } + + @Test + public void whenReplaceCharAtIndexUsingStringBuffer_thenSuccess() { + assertEquals("abcme", characterInString.replaceCharStringBuffer("abcde", 'm', 3)); } }