Reverse Words in a String when . comes
Problem : Reverse String whenever "." is encountered.
Here we are separating string to charArray and then we are checking whenever . found we are pushing string to stack and making string as empty and at last we are printing whole stack.
Ex : Input : i.am.happyOutput : happy.am.i
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
String str2=ab.next();
char arr[]=str2.toCharArray();
Stack<String> stack=new Stack<String>();
String str=new String();
for(int i=0;i<arr.length;i++)
{
if(arr[i]!='.')
str=str+arr[i];
else if(arr[i]=='.')
{
str=str+arr[i];
stack.push(str);
str="";
}
if(i==arr.length-1)
{
str=str+".";
stack.push(str);
}
}
String temp=new String();
while(stack.empty()!=true)
{
temp=temp+stack.pop();
}
temp=temp.substring(0,temp.length()-1);
System.out.println(temp);
}
}
}
0 Comments:
Post a Comment