Monday, 18 August 2014

How to reverse words in a String

Reverse words in a String


We can reverse  the words in the String by using StirngBuilder as below:

package com.interviewCodes.String;

public class ReverseWordsInString {
      
       public static void main(String args[]){
              String str="Hi I am John";
              System.out.println("Sentence before reverse:"+str);
              System.out.println("Sentence after reversing:"+reverseWords(str));
       }
      
       public static String reverseWords(String sentence){
              StringBuilder sb=new StringBuilder(sentence.length()+1);
              String[] words=sentence.split(" ");
              for(int i=words.length-1;i>=0;i--){
                     sb.append(words[i]).append(' ');
              }
              sb.setLength(sb.length()-1);
              return sb.toString();
       }
}


This is the preferred way to reverse the words in a  String.Please comment the other ways of reversing the words in a String.Thanks for reading.

No comments:

Post a Comment

How to find the String that contains only alphabets

Today we will see how to  find list of Strings that contains only alphabets. In this post I did this with and without using regular expres...