is there a simple way to split a string into words in Java?

Posted on 2003-02-23
Medium Priority
Last Modified: 2010-03-31
Is there a simple way to split a String of words in Java?? e.g. "Hello World? How are you?"
into an array of strings with each element in the array representing one word. Such that the above sentence would be:

   answer[0] = "Hello"
   answer[1] = "World?"
   answer[2] = "How"
   answer[3] = "are"
   answer[4] = "you?"

essentially i need a function that takes the string and returns the array.

Thanks alot.

Question by:benwynne

Accepted Solution

mattpeak earned 300 total points
ID: 8004304
Try this:

String answer[] = new String[5];

StringTokenizer tokens = new StringTokenizer("Hello World? How are you?");

for(int i =0;i<answer.length;i++){
  answer[i] = tokens.nextToken();

LVL 86

Expert Comment

ID: 8004522
Or if you are using Java 1.4

String question = "Hello World? How are you?";
String[] answer = question.split("\\s+");

Author Comment

ID: 8004593
Thanks alot, i've been working on a program all day and your advice helps alot. Thanks Ben

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month9 days, 14 hours left to enroll

569 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question