Ajay Kumar Ajay Kumar - 7 months ago 6
Java Question

How can i separe different words from a string "Hai how are You" using Java. Is there any easy method?

I'm trying to solve code jam Africa 2010 A problem "Reverse Words" (https://code.google.com/codejam/contest/351101/dashboard#s=p1)

I have a sentence "This is a test". How can I separate each word from the sentence and store it in an array? And how can I initialize an empty string and use it? When I tried initialize string like

str
; and proceeding with adding elements
str = str + in.next();
its giving me error that
str
not initialized. Should I compulsory initialize string with certain string like " " or "a"?

Input:

3
this is a test

foobar

all your base

Output:

Case #1: test a is this

Case #2: foobar

Case #3: base your all

[ SOLVED ]

public class Reverse {

public static void main(String[] args ){


Scanner in = new Scanner(System.in);

int cases = in.nextInt();

String empty = in.nextLine();

for(int i=0;i<cases;i++){
String s = in.nextLine();
String[] arr = s.split(" ");
for(int j=arr.length-1;j>=0;j--){
System.out.print(arr[j]+" ");

}
System.out.println();
}
}
}

Answer

You can use Split()

String[] strings = mySentance.split(" ");