Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Reverse a String without using substring()
- import java.util.Scanner;
- import java.util.Stack;
- public class StringReverseWithoutSubstring {
- public static void main(String []args) {
- Scanner scan = new Scanner(System.in);
- System.out.print("Enter string: ");
- String input = scan.nextLine();
- if (input.length() == 0) {
- System.out.println("Nothing was entered.");
- } else {
- System.out.printf("Reverse of \"%s\": ", input);
- reverseTheWord(input);
- }
- }
- public static void reverseTheWord(String word) {
- Stack<String> stack = new Stack<>();
- Stack<String> reversedString = new Stack<>();
- int index = 0;
- while (index < word.length()) {
- stack.push(String.valueOf(word.charAt(index)));
- index++;
- }
- while (!stack.isEmpty()) {
- reversedString.push(stack.pop());
- }
- reversedString.forEach(letter->{
- System.out.print(letter);
- });
- }
- }
- /* Sample Output
- Enter string: pastebin
- Reverse of "pastebin": nibetsap
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement