ISC Program: Write a program in Java to accept a string and display the new string after reversing the characters of each word.
Write a program in Java to accept a string and display the new string after reversing the characters of each word.
Sample Input:
Understanding Computer Science
Sample output:
gnidnatsrednU retupmoC ecneicS
Solution:
import java.util.Scanner;
class reverseEachWord
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence:");
String s=sc.nextLine()+" ";
String w="";
String res=" ";
for(int i=0;i<s.length();i++)
{
char ch = s.charAt(i);
if(ch==' ')
{
String m="";
for(int j=w.length()-1;j>=0;j--){
m=m+w.charAt(j);
}
res=res+m+" ";
w="";
}
else{
w=w+ch;
}
}
System.out.println("Output is:"+res.trim());
}
}