Javatpoint Logo
Javatpoint Logo

Reverse A String and Reverse Every Alternative String in Java

String manipulation is a common task in programming, and Java provides various built-in methods and techniques to perform such operations efficiently. In this section, we will explore how to reverse a string and reverse every alternative substring within it using Java.

Reversing a String:

To reverse a string in Java, we can use either the iterative or recursive approach. Let's start with the iterative method, which involves converting the string into a character array and swapping the characters from both ends.

The above code snippet reverses the given string str by swapping characters until the start and end pointers meet in the middle. Finally, we create a new string from the reversed character array and return it.

Reversing Every Alternative Substring:

To reverse every alternative substring within a string, we can split the string into substrings, identify the alternative ones, and then reverse them individually.

In the above code, we split the input string str into substrings using whitespace as the delimiter. We then iterate through the substrings, and for every alternative substring (identified by i % 2 == 1), we call the reverseString method from the previous section to reverse it. The reversed substrings are appended to the result StringBuilder object, along with a whitespace character. Finally, we trim any leading or trailing whitespaces and return the resulting string.

Here's a Java program that implements the functionalities discussed above:

ReverseStringAndAlternatives.java

Output:

Original String: Hello world, how are you today?
Reversed String: ?yadot uoy era woh ,dlrow olleH
Reversed Alternatives: Hello dlrow, how era you yadot?

In the above program, we define the reverseString method to reverse a given string using an iterative approach. Then, we define the reverseAlternativeStrings method to split the input string into substrings, reverse the alternative ones using the reverseString method, and reconstruct the final string.

In the main() method, we provide an example input string and demonstrate the output by printing the original string, the reversed string, and the string with reversed alternatives.

In this section, we have explored how to reverse a string and reverse every alternative substring within it using Java. By utilizing simple iterative or recursive techniques, combined with string manipulation, we can achieve these operations efficiently. These techniques can be applied to various programming scenarios where string reversal and manipulation are required, enabling developers to build more versatile and robust applications







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA