How to Reverse a String in Java

Configurare noua (How To)

Situatie

Example 1: Reverse a string word by word using recursion

  1. import java.util.Scanner;
  2. public class ReverseStringExample1
  3. {
  4. public static void main(String[] args)
  5. {
  6. String str;
  7. System.out.println(“Enter a string: “);
  8. Scanner scanner = new Scanner(System.in);
  9. str = scanner.nextLine();
  10. scanner.close();                                //closes the input stream
  11. String reversed = reverseString(str);
  12. System.out.println(“The reversed string is: “ + reversed);
  13. }
  14. public static String reverseString(String s)
  15. {
  16. if (s.isEmpty())                            //checks the string if empty
  17. return s;
  18. return reverseString(s.substring(1)) + s.charAt(0);                     //recursively called function
  19. }
  20. }

Output:

How to Reverse a String in Java Word by Word

Solutie

Tip solutie

Permanent

Voteaza

(8 din 17 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?