Answers for "java program to reverse each word in string"

2

Reverse a string in java word by word

// Reverse a string in java word by word
import java.util.Scanner;
public class ReverseStringWordByWord 
{
   public static void main(String[] args) 
   {
      String strWord = "";
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter a string: ");
      String strGiven = sc.nextLine();     
      char[] chArray = strGiven.toCharArray();
      System.out.println("Reversed string word by word: ");
      for(int a = 0; a < (chArray.length); a++)
      {
         if(chArray[a] != ' ')
         {
            strWord = strWord + chArray[a];
         }
         else
         {
            for(int b = strWord.length(); b > 0; b--)
            {
               System.out.println(strWord.charAt(b - 1));       
            }
            System.out.print(" ");
            strWord = "";
         }
      }
      for(int b = strWord.length(); b > 0; b--)
      {
         System.out.println(strWord.charAt(b - 1));       
      }
      sc.close();
   }
}
Posted by: Guest on February-19-2021

Code answers related to "java program to reverse each word in string"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language