Reverse Middle Words in a String
You are given string S as a input. You has to reverse all the words in the input except first and last word.
INPUT
"hello how are you"
OUTPUT
hello woh era you
JAVA Solution
import java.util.*;
public class Hello {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String str = s.nextLine();
String str1[] = str.split(" ");
int i, len = str1.length, len1 = len-1;
for(i=0;i<len;i++)
{
if(i!=0&&i!=len1)
{
StringBuilder sb = new StringBuilder(str1[i]);
System.out.print(sb.reverse().toString()+" ");
}
else
System.out.print(str1[i]+" ");
}
}
}
If anyone come up with better solution or having queries leave it in comment.
Keep Programming....!!!
INPUT
"hello how are you"
OUTPUT
hello woh era you
JAVA Solution
import java.util.*;
public class Hello {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String str = s.nextLine();
String str1[] = str.split(" ");
int i, len = str1.length, len1 = len-1;
for(i=0;i<len;i++)
{
if(i!=0&&i!=len1)
{
StringBuilder sb = new StringBuilder(str1[i]);
System.out.print(sb.reverse().toString()+" ");
}
else
System.out.print(str1[i]+" ");
}
}
}
If anyone come up with better solution or having queries leave it in comment.
Keep Programming....!!!
Comments
Post a Comment