1.

Write a Java program to reverse a string.

Answer» CLASS InterviewBit{ PUBLIC static void main(String[] ARGS){ //Input String String STR = "Welcome to InterviewBit"; //Pointers. int i = 0, j = str.length()-1; //Result character array to store the reversed string. char[] revString = new char[j+1]; //Looping and reversing the string. while(i < j){ revString[j] = str.charAt(i); revString[i] = str.charAt(j); i++; j--; } //Printing the reversed String. System.out.println("Reversed String = " + String.valueOf(revString)); }}

In the above code, we are storing the last character from the string to the first and the first value to the last in the output character array. And doing the same THING in the loop for the remaining 2nd to n-1 characters. This is how the string will be reversed.



Discussion

No Comment Found