Added the code of Replace char in a string at specific index (#5869)

* 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
This commit is contained in:
Shashank agarwal 2018-12-20 10:19:27 +05:30 committed by KevinGilmore
parent 6abaf50ab5
commit 547f99925f
3 changed files with 45 additions and 1 deletions

View File

@ -2,7 +2,7 @@
## Java Strings Cookbooks and Examples
### Relevant Articles:
### Relevant Articles:
- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings)
- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream)
- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner)

View File

@ -0,0 +1,21 @@
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 replaceCharStringBuilder(String str, char ch, int index) {
StringBuilder myString = new StringBuilder(str);
myString.setCharAt(index, ch);
return myString.toString();
}
public String replaceCharStringBuffer(String str, char ch, int index) {
StringBuffer myString = new StringBuffer(str);
myString.setCharAt(index, ch);
return myString.toString();
}
}

View File

@ -0,0 +1,23 @@
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));
}
@Test
public void whenReplaceCharAtIndexUsingStringBuilder_thenSuccess(){
assertEquals("abcme",characterInString.replaceCharStringBuilder("abcde",'m',3));
}
@Test
public void whenReplaceCharAtIndexUsingStringBuffer_thenSuccess(){
assertEquals("abcme",characterInString.replaceCharStringBuffer("abcde",'m',3));
}
}