Program to reverse each word in a sentence

Simple java program to reverse each word in a sentence, not the whole sentence. This type question are also asked in technical round of top company's interview. Here is the solution and explanation. Explanation- 1st the sentence will be split into words, then each word is reversed, after that nextword will be processed.

Input:

Techie Tet

Output:

eihceT teT

 

class ReverseWord
   {
     public static void main(String args[])
     {
	int len,i;
	String strnew="";
	String str="Techie Tet";
	char[] cs=new char[9];
	String[] strarray= str.split("\\s");

	 for(String s:strarray)
	  {
	    len=s.length();
	    strnew=strnew+"";
            for(i=0;i < s.length();i++)
	      {
              cs[i]=s.charAt(len-1);
              len--;
              strnew=strnew+cs[i];
	      }
          }
        System.out.println(strnew);
       }
  }

Result displayed by the above program:

eihceT teT

 

Related post:

Program to Reverse a string

Program to Reverse a Number