In this article, we will see how to reverse a String in place using traditional & Java 8 Stream approaches
1. Traditional approach :
- Here, we will create a StringBuilder object with the given input String after trimming for any leading or trailing white-spaces
- Iterate through the string length for reversing the string by swapping approach
- Finally, test the reverse program with different set of input strings like
- odd length string
- even length string
- leading white-spaces
- trailing white-spaces
- leading & trailing white-spaces
- null
- empty string
- empty string with white–spaces
ReverseStringInPlace.java
package in.bench.resources.reverse.string;
public class ReverseStringInPlace {
// main() method
public static void main(String[] args) {
// strings in different formats
String[] strArrays = {
"India", // odd length string
"France", // even length string
" China", // leading white-spaces
"Bhutan ", // trailing white-spaces
" America ", // leading & trailing white-spaces
null, // null
"", // empty string
" " // empty string with white-spaces
};
// invoke/test & print to console
for(String str : strArrays) {
System.out.println("Original String :- " + str);
System.out.println("Reversed String :- " + reverseString(str) + "\n");
}
}
/**
* method to reverse the string using traditional for-loop
*
* @param input
* @return
*/
private static String reverseString(final String input) {
if(null == input || input.isEmpty() || input.trim().length() == 0) {
return "INVALID string";
}
// local variable
StringBuilder sbd = new StringBuilder(input.trim());
// get length of input String
int length = input.trim().length();
// iterate through each characters of input String
for(int index = 0; index < length/2; index++) {
// get in-place character for swapping
final char leftChar = sbd.charAt(index);
final int rightCharIndex = length - 1 - index;
final char rightChar = sbd.charAt(rightCharIndex);
// actual swapping
sbd.setCharAt(index, rightChar);
sbd.setCharAt(rightCharIndex, leftChar);
}
// return reversed string
return sbd.toString();
}
}
Output :
Original String :- India
Reversed String :- aidnI
Original String :- France
Reversed String :- ecnarF
Original String :- China
Reversed String :- anihC
Original String :- Bhutan
Reversed String :- natuhB
Original String :- America
Reversed String :- aciremA
Original String :- null
Reversed String :- INVALID string
Original String :-
Reversed String :- INVALID string
Original String :-
Reversed String :- INVALID string
2. Java 8 Stream approach :
- Iterate through the string length using range() method of IntStream starting from index 0 till length minus one (where start-index is inclusive & end-index is exclusive)
- Map the object in reverse order using Stream.mapToObj() method and collect it to new StringBuilder object using constructor–references
- Finally, test the reverse program with different set of input strings as shown in the above example
ReverseStringInPlaceUsingJava8Stream.java
package in.bench.resources.reverse.string;
import java.util.Arrays;
import java.util.stream.IntStream;
public class ReverseStringInPlaceUsingJava8Stream {
// main() method
public static void main(String[] args) {
// strings in different formats
String[] strArrays = {
"India", // odd length string
"France", // even length string
" China", // leading white-spaces
"Bhutan ", // trailing white-spaces
" America ", // leading & trailing white-spaces
null, // null
"", // empty string
" " // empty string with white-spaces
};
// invoke/test & print to console
Arrays.stream(strArrays).forEach(str -> {
System.out.println("Original String :- " + str);
System.out.println("Reversed String :- " + reverseString(str) + "\n");
});
}
/**
* method to reverse the string using Java 8 Stream API
*
* @param input
* @return
*/
private static String reverseString(final String input) {
if(null == input || input.isEmpty() || input.trim().length() == 0) {
return "INVALID string";
}
return IntStream
.range(0, input.length())
.mapToObj(index -> input.charAt(input.length() - 1 - index))
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
.toString();
}
}
Output :
Original String :- India
Reversed String :- aidnI
Original String :- France
Reversed String :- ecnarF
Original String :- China
Reversed String :- anihC
Original String :- Bhutan
Reversed String :- natuhB
Original String :- America
Reversed String :- aciremA
Original String :- null
Reversed String :- INVALID string
Original String :-
Reversed String :- INVALID string
Original String :-
Reversed String :- INVALID string
Related Articles :
- Java 8 – Count and print number of lines and words in a text file
- Java 8 – Count and print number of repeated word occurrences in a text file
- Java 8 – Count and print number of repeated character occurrences in a String
- Java 8 – Count and print number of Vowels and Consonants in a String
- Java 8 – Reverse each words in a String using Stream and Collectors
- Java 8 – Reverse complete/entire String using Stream and Collectors
- Java 8 – How to Reverse a String in place ?
- Java 8 – Remove input-ted Character from a given String
- Java 8 – How to split a String and Collect to any Collection ?
- Java 8 – How to check whether given String contains only Alphabets or Letters ?
- Java 8 – How to check whether given String contains only Digits ?
- Java 8 – How to check whether given String contains Alphanumeric characters only ?
- Java 8 – How to convert first character of every word to Uppercase ?
- Java 8 – How to convert duplicate characters to Uppercase in a String ?
- Java 8 – How to remove special characters from String ?
- Java 8 – How to remove last comma (,) from String ?
- Java 8 – How to count length of last word in a String ?
References:
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html
- https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html
- https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
Happy Coding !!
Happy Learning !!