Added Character Array method (#5965)
* Added the code of Replace char in a string at specific index * added test cases * Renamed the Test class name end with UnitTest * Renamed the Test class name end with UnitTest * Renamed the Test class name end with UnitTest * Replaced README with the upstream repo * Added Char Array Method
This commit is contained in:
parent
be2e45b0a5
commit
fda7ff2690
|
@ -1,11 +1,19 @@
|
|||
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);
|
||||
return myString;
|
||||
}
|
||||
|
||||
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);
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
package com.baeldung.string;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ReplaceCharInStringUnitTest {
|
||||
|
@ -11,6 +12,11 @@ public class ReplaceCharInStringUnitTest {
|
|||
assertEquals("abcme", characterInString.replaceCharSubstring("abcde", 'm', 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReplaceCharAtIndexUsingCharArray_thenSuccess() {
|
||||
assertEquals("abcme", characterInString.replaceCharUsingCharArray("abcde", 'm', 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReplaceCharAtIndexUsingStringBuilder_thenSuccess() {
|
||||
assertEquals("abcme", characterInString.replaceCharStringBuilder("abcde", 'm', 3));
|
||||
|
|
Loading…
Reference in New Issue