Saturday, 11 August 2018

Reverse a String in Java


There are numerous methods for turning around a String in Java for reasons unknown you may have. Today, we will take a gander at a couple of basic methods for turning around a String in Java. For instance, the string “Reverse Me" once turned around will be “eM esreveR”. We will begin by taking a gander and no more conventional technique with minimal assistance from outer Java classes.

import java.util.Scanner;

public class ReverseString
{
public static void main(String[] args)
{
System.out.println("Enter string to reverse:");

Scanner read = new Scanner(System.in);
String str = read.nextLine();
String reverse = "";


for(int i = str.length() - 1; i >= 0; i--)
{
reverse = reverse + str.charAt(i);
}

System.out.println("Reversed string is:");
System.out.println(reverse);
}
}




In the above code, we are essentially perusing in a String from the client after which we will start a cycle circle that will fabricate the new switched String. This is done in the "for" loop by getting the characters of the first String separately from the end by utilizing the "charAt" capacity of the String class and linking them to another String by utilizing the "+" operator.

Another method which is also similar but uses the Java StringBuilder class instead:

import java.util.Scanner;

public class ReverseString
{
    public static void main(String[] args)
    {
        System.out.println("Enter string to reverse:");
        
        Scanner read = new Scanner(System.in);
        String str = read.nextLine();
        
        StringBuilder sb = new StringBuilder();
        
        for(int i = str.length() - 1; i >= 0; i--)
        {
            sb.append(str.charAt(i));
        }
        
        System.out.println("Reversed string is:");
        System.out.println(sb.toString());
    }
}



Fundamentally the same as the past strategy, the main distinction is that we are utilizing the "append" capacity of the Java StringBuilder class in the emphasis circle rather to connect the characters to shape the turned around String.

Obviously there is as yet a simpler alternate way to do it and that is essentially utilize the Java StringBuilder class "reverse" function.

import java.util.Scanner;

public class ReverseString
{
    public static void main(String[] args)
    {
        System.out.println("Enter string to reverse:");
        
        Scanner read = new Scanner(System.in);
        String str = read.nextLine();
        
        StringBuilder sb = new StringBuilder(str);
        
        System.out.println("Reversed string is:");
        System.out.println(sb.reverse().toString());
    }
}


What we have seen above are only a couple of approaches to switch a String in Java. The fact is that there are numerous conceivable approaches to switch a String in Java and toward the day's end, it comes down to singular prerequisites, confinements and what works best for you.

0 comments:

Post a Comment