Advertisement
binibiningtinamoran

StringReverseWithoutSubstring.java

Jun 3rd, 2019
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 KB | None | 0 0
  1. // Reverse a String without using substring()
  2.  
  3. import java.util.Scanner;
  4. import java.util.Stack;
  5.  
  6. public class StringReverseWithoutSubstring {
  7.  
  8.     public static void main(String []args) {
  9.  
  10.         Scanner scan = new Scanner(System.in);
  11.         System.out.print("Enter string: ");
  12.         String input = scan.nextLine();
  13.         if (input.length() == 0) {
  14.             System.out.println("Nothing was entered.");
  15.         } else {
  16.             System.out.printf("Reverse of \"%s\": ", input);
  17.             reverseTheWord(input);
  18.         }
  19.     }
  20.  
  21.     public static void reverseTheWord(String word) {
  22.         Stack<String> stack = new Stack<>();
  23.         Stack<String> reversedString = new Stack<>();
  24.         int index = 0;
  25.         while (index < word.length()) {
  26.             stack.push(String.valueOf(word.charAt(index)));
  27.             index++;
  28.         }
  29.  
  30.         while (!stack.isEmpty()) {
  31.             reversedString.push(stack.pop());
  32.         }
  33.  
  34.         reversedString.forEach(letter->{
  35.             System.out.print(letter);
  36.         });
  37.     }
  38.  
  39. }
  40.  
  41. /* Sample Output
  42. Enter string: pastebin
  43. Reverse of "pastebin": nibetsap
  44. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement