Program to display the input string from backward
Display the input string in reverse order
The program displays the input String in reverse order and for this action, you can use the substring method.The syntax for the built_in method substring is:-
Syntax :
public String substring(int begIndex, int endIndex)
Parameters :
beginIndex : the begin index, inclusive.
endIndex : the end index, exclusive.
Return Value :
The specified substring.
If you need some data from the user then you need to import the Scanner class. Here 'Scanner' class, the built-in class inside the 'util' package of 'java' project is imported to get value from the keyboard.
import java.util.Scanner; //Importing Scanner class to get input from the user
import java.lang.String; //Importing Scanner class from the package lang of java project
public class Backwards
{
// instance variables
private String x;
public void reverse()
{
System.out.println("Enter a String"); //Instruction to user
x= new Scanner(System.in).nextLine();
int a= x.length(); //counting number of digit in value of variable x and storing in variable a
//declaring and initializing the variable
int b=0;
int c=1;
String s1=" "; //declaring and initializing the variable s1
for(int i=1;i<=a;i++)
{
String s= x.substring(b,c); //Built_in method used to abstract fixed characters from the provided string
s1=s+s1;
b++;
c++;
}
System.out.println("The string in reverse is ");
System.out.println(s1);
}
public static void main(String []args)
{
Backwards r= new Backwards();
r.reverse();
}
}
The output of the above program looks like this:-
Comments
Post a Comment