Wednesday, October 28, 2015

Reverse String in Java (Without using StringBuffer reverse() function)

Here is the code to print the reverse of the entered string in Java without using the predefined function of StringBuffer class. The Output is shown below and followed by the code:




import java.util.Scanner;
public class ReverseString {
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Program to Print Reverse of a string without using any API");
        System.out.println("----SPACES NOT ALLOWED----");
        System.out.print("Enter the String:- "); //taking string from user
        String s = sc.next();
        int i,j,k;
        int n = s.length();
        char[] c = new char[n]; //converting into character array
        c = s.toCharArray();
        char[] c1 = new char[n];
        //traversing from back to front of string and assigning it to new array
        for(i=n-1,j=0;i>=0;j++,i--) 
        {
            c1[j] = c[i];
        }
        String rev = new String(c1);
        System.out.println("The Reverse of String is:- \t"+rev); //Printing the reverse String
    }
}

No comments:

Post a Comment