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
- import java.util.regex.Pattern;
- public class ReverseOfWordPart2 {
- static String rev = "";
- public static void main(String[] args) {
- String str = "the sky is blue in india";
- System.out.println("The original string is: " + str);
- Pattern p = Pattern.compile("\\s");
- String[] temp = p.split(str);
- for (int i = 0; i < temp.length; i++) {
- rev = " " + temp[i] + rev;
- }
- System.out.println("The reversed string is: " + rev);
- }
- }
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
- // Java Program to reverse a String // without using inbuilt String function
- import java.util.regex.Pattern;
- public class ReverseOfWord {
- // Method to reverse words of a String
- static String reverseWords(String str)
- {
- // Specifying the pattern to be searched
- Pattern pattern = Pattern.compile("\\s");
- // splitting String str with a pattern
- // (i.e )splitting the string whenever their
- // is whitespace and store in temp array.
- String[] temp = pattern.split(str);
- String result = "";
- // Iterate over the temp array and store
- // the string in reverse order.
- for (int i = 0; i < temp.length; i++) {
- if (i == temp.length - 1)
- result = temp[i] + result;
- else
- result = " " + temp[i] + result;
- }
- return result;
- }
- // Driver methods to test above method
- public static void main(String[] args)
- {
- String s1 = "Welcome to geeksforgeeks";
- System.out.println(reverseWords(s1));
- String s2 = "I love Java Programming";
- System.out.println(reverseWords(s2));
- }
- }
No comments:
Post a Comment