Programming Examples

Java program to reverse each words of string


write a java program which accept a string from user and reveres the each words of string and form a new string.

Sample Input:

ram is a good boy

Sample Output:

mar si a doog yob

Solution:

import java.util.*;
class RevWord
{
    
    public static void main(String arr[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter Any String ");
        String str1=sc.nextLine();
        String rev="";
        for(int a=0;a<str1.length();a++)
        {
            if(str1.charAt(a)==' ')
            {
                System.out.print(rev+" ");
                rev="";
            }
            else
            {
                rev=str1.charAt(a)+rev;
            }
            
        }
        System.out.print(rev);
    }
}
Output

Enter Any String 

ram is a good boy

mar si a doog yob

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz