Write a program in JAVA to input a sentence reverse every word and print .
Please answer someone.
Answers
import java.util.*;
class reverse_word
{
public void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence");
String s=sc.nextLine();
s=s+" ";
String rev="";
int l=s.length();
String w="";
for(int i=0;i<l;i++)
{
char ch=s. charAt(i);
if(ch!=' ')
{
w=ch+w;
}
else
{
System.out.print(w+" ");
w="";
}
}
}
}
→ We are taking a sentence as input .
→ Hence begin with "sc.nextLine()" .
→ Then we calculate the length of the string .
→ Then we run a for-loop extracting every character .
→ Concat function reverses every word.
→ The line "w=ch+w" is the critical line which helps in reversing the words .
Answer:
Java Program to reverse each word in String
public class StringFormatter {
public static String reverseWord(String str){
String words[]=str.split("\\s");
String reverseWord="";
for(String w:words){
StringBuilder sb=new StringBuilder(w);
StringBuilder sb=new StringBuilder(w);sb.reverse();
reverseWord+=sb.toString()+" ";