Thursday, 21 May 2015

How to Reverse Words of a String In Java ?

How to reverse words in a string in java ?

    This is often a programming question in java interviews. When i was fresher, i got this program in written test. Unfortunately, i didn't know how to solve at that point of time.

Lets see how to solve. First of all, how do you find the words in a string or sentence. In sentences, words are separated by spaces (" ").
   
    So to solve the problem, first you need to split the given string based on the delimiter - space i.e (" "). Java has a method in String class for splitting strings. i.e split().
   
    The split method has following syntaxes.
   
    1. public String[] split(String regex)
    2. public String[] split(String regex, int limit)
   
    The split(String regex) takes an regular expression pattern as argument. A regular expression pattern is a string which follows regular expression grammar. for example, regular expression for string aaaaa is "a{5}", which means a has occurred 5 times.
   
    Now consider, you have given a string "Hello Good Morning". First split this string using split() method. The split(" ") method gives a String array so reverse the array to get the desired output.
   
    The program is
   
package com.speakingcs.practice;

public class ReverseWords {

    public static void main(String[] args) {
   
        // Test String

        String str = "Hello Good Morning";
      

        // Split based on space. Words are seperated by Spaces only.

        String[] arr = str.split(" ");
       

        // the below for loop is for reversing the string array.

        for(int i = arr.length-1; i >= 0 ; i--) {

            System.out.print(arr[i] + " ");

        }
    }
}

Output: Morning Good Hello


Another Approach :

You can also use StringTokenizer Class to split the string. StringTokenizer class has a 2 argument constructor which takes the actual string as 1st argument, delimiter as 2nd argument. delimiters are nothing but strings which acts as separators.

The program is

package com.speakingcs.practice;

import java.util.StringTokenizer;

public class ReverseWords {

    public static void main(String[] args) {
    
        // Test String

        String str = "Hello Good Morning";
              
        splitStrig(str," ");

    }


    private static void splitStrig(String str, String delimiter) {
          
        StringTokenizer st = new StringTokenizer(str, delimiter);
       

        int noOfWords = st.countTokens();
       
        String[] arr = new String[noOfWords];
      
        int i = 0; 
     
        while(st.hasMoreTokens()) {

            arr[i++] = st.nextToken();
        }
       
        // the below for loop is for reversing the string array.

        for(i = arr.length-1; i >= 0 ; i--) {

            System.out.print(arr[i] + " ");

       }
      
    }

}

Output is : Morning Good Hello

Some More Examples:

What if the interviewer asks, reverse the words which are not numbers. for example, given a string "abcd1234efgh1234ijkl1234mno", and expected output is "mno1234ijkl1234efgh1234abcd". How can you do this? The answer is below. Here pass 1234 as delim.
private static void splitStrings(String str, String delim) {

        // TODO Auto-generated method stub

        String[] arr = str.split(delim);
      
        for(int i = arr.length-1; i >= 0 ; i--) {

            System.out.print(arr[i] + delim);

        }

}

Input is : abcd1234efgh1234ijkl1234mno
Output is : mno1234ijkl1234efgh1234abcd1234

Try this:

Given a string, "abcd12efgh1234ijk5678mno", split the string based on number. Expected output is abcd,efgh,ijk,mno.

For the above case we need to use regualr expression as delimiter. So the delimiter is "\\d{1,}". "\\d{1,}" means, any digit or any number which has any number of digits. i.e 1, 12, 123, 1234, 12356, ...... . The solution for this is

Here delim is "\\d{1,}".
private static void splitStrings(String str, String delim) {

        // TODO Auto-generated method stub

        String[] arr = str.split(delim);

        System.out.println();

        for(int i = arr.length-1; i >= 0 ; i--) {

            System.out.print(arr[i]+" ");

        }

    }

Input is : abcd1234efgh1234ijkl1234mno
Output is : mno ijkl efgh abcd
      

2 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. Thanks it is useful for freshers in Java. Keep doing

    ReplyDelete

Note: only a member of this blog may post a comment.