Ajay Kumar Ajay Kumar - 1 year ago 42
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

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


this is a test


all your base


Case #1: test a is this

Case #2: foobar

Case #3: base your all


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]+" ");


Answer Source

You can use Split()

String[] strings = mySentance.split(" ");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download