Monday, June 3, 2019

Reverse words in a given String in Java

Q. To Reverse words in a given String in Java


Input : "Welcome to geeksforgeeks"
Output : "geeksforgeeks to Welcome"

Input : "I love Java Programming"
Output :"Programming Java love I"


===========================================

YouTube video:-



Our code :
  • Example No.1
  1. import java.util.regex.Pattern;
  2. public class ReverseOfWordPart2 {
  3. static String rev = "";
  4.    public static void main(String[] args) {
  5.       String str = "the sky is blue in india";
  6.   
  7.       System.out.println("The original string is: " + str);
  8.       
  9.       Pattern p = Pattern.compile("\\s");
  10.       
  11.       String[] temp = p.split(str);
  12.       
  13.       
  14.       for (int i = 0; i < temp.length; i++) {
  15.         
  16.             rev = " " + temp[i] + rev;
  17.       }
  18.       System.out.println("The reversed string is: " + rev);
  19.    }
  20. }
O/P
The original string is: the sky is blue in india
The reversed string is:  india in blue is sky the
=============================================================================
  • Example No.2
  1. // Java Program to reverse a String // without using inbuilt String function 
  1. import java.util.regex.Pattern; 
  2. public class ReverseOfWord { 
  3. // Method to reverse words of a String 
  4. static String reverseWords(String str) 
  5. { 
  6. // Specifying the pattern to be searched 
  7. Pattern pattern = Pattern.compile("\\s"); 
  8. // splitting String str with a pattern 
  9. // (i.e )splitting the string whenever their 
  10. // is whitespace and store in temp array. 
  11. String[] temp = pattern.split(str); 
  12. String result = ""; 
  13. // Iterate over the temp array and store 
  14. // the string in reverse order. 
  15. for (int i = 0; i < temp.length; i++) { 
  16. if (i == temp.length - 1) 
  17. result = temp[i] + result; 
  18. else
  19. result = " " + temp[i] + result; 
  20. } 
  21. return result; 
  22. } 
  23. // Driver methods to test above method 
  24. public static void main(String[] args) 
  25. { 
  26. String s1 = "Welcome to geeksforgeeks"; 
  27. System.out.println(reverseWords(s1)); 
  28. String s2 = "I love Java Programming"; 
  29. System.out.println(reverseWords(s2)); 
  30. } 
  31. } 






No comments:

Post a Comment