Java reverse string without using inbuilt functions


 

Java reverse string without using inbuilt functions

In this tutorial, you will learn how to reverse string without using any inbuilt functions.

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));
}
}

Ads