Home Tutorial Java Core Java reverse string without using inbuilt functions

 
 

Share on Google+Share on Google+
Java reverse string without using inbuilt functions
Posted on: December 21, 2012 at 12:00 AM
Advertisement
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));
}
}
Advertisement

Related Tags for Java reverse string without using inbuilt functions:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 21, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com