36 Views0 Thanks

How to reverse a given string

Home Testing Forums Programing Language Java How to reverse a given string

Viewing 2 posts - 1 through 2 (of 2 total)

  • Anonymous
    Inactive

    In Java, What could be the best possible ways of reversing the given string.


    Shashi Kumar
    Participant

    We can reverse the string by splitting the string characters into an char array and then looping through the array. Below is the code where you can reverse the string Hello World in Java.

    String string = "Hello World";
    	char[] stringCharArray = string.toCharArray();
    	String reverse = "";
    	for(int i=stringCharArray.length-1; i>=0 ; i-- ) {
    		reverse = reverse + stringCharArray[i];
    	}
    	System.out.println(reverse);

    Code Explanation : At first we are defining the string variable which contains the string Hello world. We use a string method toCharArray which converts the string into a char array. We can use the for loop in decreasing order, it start with the char Array Size – 1 and decrease one time in each iteration. You can define an empty string reverse and append each character to the reverse string.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login or Register