Q Write a program to reverse each word in an inputted string.
Example: Hello Students becomes olleH stnedutS
SOLUTION:
import java.lang.String;
import java.lang.StringBuffer;
import java.util.Scanner;
class q4
{
public static void main(String args[])
{
String str;
String str1 = new String();
StringBuffer temp;
int count = 0,i,j,k = 0;
int b,e;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String: ");
str = sc.nextLine();
str = str.trim();
for(i=0;i<str.length();++i)
{
if(str.charAt(i) == ' ')
++count;
}
if(count == 0)
{
temp = new StringBuffer(str);
temp.reverse();
System.out.println(temp);
System.exit(0);
}
b = 0;
for(i=0;i<str.length();i++)
{
if(str.charAt(i) == ' ')
{ ++k;
e = i;
temp = new StringBuffer(str.substring(b,e));
temp.reverse();
str1 = str1.concat(String.valueOf(temp));
str1 = str1.concat(" ");
b = e + 1;
if(k == count)
{ temp = new StringBuffer(str.substring(b));
temp.reverse();
str1 = str1.concat(String.valueOf(temp));
break;
}
}
} System.out.println(str1);
}
}
OUTPUT:
Comments
Post a Comment