3
Java - Reverse String - alternate
source link: http://mussatto.github.io/java/string/reverse/2018/06/21/string-reverse-java-2.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Java - Reverse String - alternate
This is an alternate solution for reversing Strings in java
The algorithm:
- Split the String into an array with all the characters
- Iterate throught the array, starting from the last position and adding into a new string
public static String reverse(String s1) {
if(isNull(s1)){
return null;
}
StringBuilder stringBuilder = new StringBuilder();
String[] splitted = s1.split("");
for (int i = splitted.length - 1; i >= 0; i--) {
stringBuilder.append(splitted[i]);
}
return stringBuilder.toString();
}
Tests:
@Test
public void reverse1(){
String entry = "ABCDEF";
String expected = "FEDCBA";
String result = StringReverserByConcat.reverse(entry);
assertEquals(expected, result);
}
@Test
public void reverseNull(){
String entry = null;
String expected = null;
String result = StringReverserByConcat.reverse(entry);
assertEquals(expected, result);
}
@Test
public void reverseEmpty(){
String entry = "";
String expected = "";
String result = StringReverserByConcat.reverse(entry);
assertEquals(expected, result);
}
Source code: Reverse Class Source code: Reverse Test
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK