Reverse words in a given string

 

Given a String of length N reverse the words in it. Words are separated by dots.
Input:
The first line contains T denoting the number of testcases. Then follows description of testcases. Each case contains a string containing spaces and characters.
Output:
For each test case, output a single line containing the reversed String.
Constraints:
1<=T<=20
1<=Lenght of String<=2000

Example:
Input:
2
i.like.this.program.very.much
pqr.mno
Output:
much.very.program.this.like.i
mno.pqr


public class ReverseWords {
    
 private static final Scanner scanner = new Scanner(System.in);

 public static void main(String[] args) {
  
  ArrayList<String> list = new ArrayList<String>();
  int n = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
        
  for (int k=0;k<n;k++) {
   String str = scanner.nextLine();

   String[] strArr = str.split("\\.");
   str = "";
   for(int i=strArr.length-1;i>=0;i--) {
    if(i == 0)
     str = str + strArr[i];
    else
     str = str + strArr[i] +".";
   }
   list.add(str);
  }
  
  for (String string : list) {
   System.out.println(string);
  }
 }
}

INPUT:

2
i.like.this.program.very.much
pqr.mno

OUTPUT:

much.very.program.this.like.i
mno.pqr

No comments:
Write comments