» » Reverse words in a String

1. Java Interview Program to Reverse words in a string


  1. package com.instaceofjava;
  2.  
  3. public class ReverseString {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. String strng= "Instance of Java ";
  8.  
  9. String str[] =strng.split(" ");
  10.  
  11. String result="";
  12.  
  13. for(int i=str.length()-1;i>=0;i--){
  14.  
  15. result += str[i]+" ";
  16.  
  17. }
  18.  
  19. System.out.println(result );
  20. }
  21. }
Output:

  1. Java of Instance



2. Java Interview Program to Reverse words in a string


  1. package com.instaceofjava;
  2.  
  3. public class ReverseString {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. String strng= "Instance of Java ";
  8.  
  9. StringBuilder sb = new StringBuilder(strng.length() + 1);
  10.  
  11.   String[] words = strng.split(" ");
  12.  
  13.   for (int i = words.length - 1; i >= 0; i--) {
  14.          sb.append(words[i]).append(' ');
  15.    }
  16.     
  17.     sb.setLength(sb.length() - 1); 
  18.  
  19.    String result= sb.toString();  
  20.  
  21.     System.out.println(result);

  22. }
  23. }
Output:

  1. Java of Instance

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu