1

If I have a String variable containing a sentence, does anybody know how to extract the words from that sentence and store them in an array?

e.g. Take the String ("Hello World")

and store it like ["Hello","World"]

This is what I have been trying, but it doesn't work at all:

int newWord = 0;
String sentence;
String[] words;

for(count = 0; count < sentence.length(); count++)
    {
        words[newWord].charAt(count) = sentence.charAt(count);

        if(sentence.charAt(count) == ' ' )
        {
            newWord++;
        }
    }
1
  • 2
    You can do what Elliott said below or also "Hello World".split(" "); Commented Oct 16, 2015 at 23:13

1 Answer 1

4

You can use String.split(String) and a regular expression like \\s+ (for one or more whitespace characters). Something like,

String[] words = "Hello World".split("\\s+");
System.out.println(Arrays.toString(words));

Output is (as requested)

[Hello, World]
Sign up to request clarification or add additional context in comments.

2 Comments

@ElliotFrisch Thank you. Will this work if I am receiving input from the user and I cannot know the value of the String beforehand?
Yes. Replace "Hello World" with a String reference variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.