Home Tutorial Java Core Java reverse string without using inbuilt functions

 
 

Java reverse string without using inbuilt functions
Posted on: December 21, 2012 at 12:00 AM
In this tutorial, you will learn how to reverse string without using any inbuilt functions.

Java reverse string without using inbuilt functions

In this tutorial, you will learn how to reverse string without using any inbuilt functions. Here, we have created a method to reverse the string and returns a new string with reverse order. In the main method, we have allowed the user to enter the string and invoked the method.

Example:

import java.util.*;

class StringExample 
{
public static int getLength(String myString) {
int i = 0;
try {
while (true) {
myString.charAt(i);
i++;
}
} catch (IndexOutOfBoundsException e) {
return i;
}
}
public static String reverseString(String s) {
char[] reverseStringArray = new char[s.length()];
for (int i = s.length() - 1, j = 0; i != -1; i--, j++) {
reverseStringArray[j] = s.charAt(i);
}
return new String(reverseStringArray);
}

public static void main(String[] args) 
{
Scanner input=new Scanner(System.in);
System.out.print("Enter string:");
String str=input.nextLine();
System.out.println(getLength(str));
System.out.println(reverseString(str));
}
}

Related Tags for Java reverse string without using inbuilt functions:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.