There are 2 ways to reverse a string
- String reversal without using function
- String reversal with function
String reversal without using function
package stringReversal; import java.util.Scanner; public class StringReversal { int stringLength; static String stringToReverse; String reversedString=""; public String stringReverse(String name) { stringLength = name.length(); for(int i=stringLength-1; i>=0;i--) { reversedString+=name.charAt(i); } return reversedString; } public static void main(String[] args) { StringReversal stringReversal = new StringReversal(); Scanner scanner = new Scanner(System.in); System.out.print("Enter the string to reverse :"); stringToReverse = scanner.nextLine(); System.out.println("Reversed String is :" +stringReversal.stringReverse(stringToReverse)); } }
Output
Enter the string to reverse :Make the string reversed Reversed String is :desrever gnirts eht ekaM
String reversal with function
package stringReversal; import java.util.Scanner; public class StringReversalWithFunction { static String stringToReverse; String reversedString=""; StringBuffer stringReverseWithFunction(StringBuffer stringBufferObject) { return stringBufferObject.reverse(); } public static void main(String[] args) { StringReversalWithFunction stringReversalWithFunction = new StringReversalWithFunction(); Scanner scanner = new Scanner(System.in); System.out.print("Enter the string to reverse :"); stringToReverse = scanner.nextLine(); System.out.println("Reversed String is :"+stringReversalWithFunction. stringReverseWithFunction(new StringBuffer(stringToReverse))); } }
Output
Enter the string to reverse :Make this string to reverse Reversed String is :esrever ot gnirts siht ekaM
Comments
Post a Comment