Monday, 17 July 2017

Java | Reverse a String without using String class function


package com.java.tricks;
import java.lang.reflect.Field;
public class ReverseString {

     /**
      * This method is used to reverse string without using any string class method.
      */
     private static void reverseString(String value) {
           try {
               
                /** to access the private value[] array of String class. */
                Field field = String.class.getDeclaredField("value");

                /** Grant the access to access the field value. */
                field.setAccessible(true);

                /** Access the value array from the String class. */
                char[] array = (char[]) field.get(value);
                int i = 0; int j = array.length-1;

                /** Reverse the array values to reverse it. */
                while(i<j) {
                     char temp = array[i];
                     array[i] = array[j];
                     array[j] = temp;
                     i++; j--;
                }
               
                /** Set the reversed array into the String Object. */
                field.set(value, array);
           } catch (NoSuchFieldException | SecurityException |
                     IllegalArgumentException | IllegalAccessException e) {
                System.err.println(e.getCause());
           }
     }

     /**
      * Driver method to reverse a String.
      */
     public static void main(String[] args) {
           String value = "geeksforgeeks";
           System.out.println(value);
           reverseString(value);
           System.out.println(value);
     }
}

2 comments:

  1. Thanks for a great answer. Couldn't find better than this anywhere else.

    ReplyDelete
    Replies
    1. For updates keep following: http://algorithmforum.blogspot.in/

      Delete

Related Posts Plugin for WordPress, Blogger...