?
Solved

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

Posted on 2003-02-23
3
Medium Priority
?
157 Views
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.

Ben
0
Comment
Question by:benwynne
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 

Accepted Solution

by:
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();
}

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8004522
Or if you are using Java 1.4

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

Author Comment

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

Featured Post

New benefit for Premium Members - Upgrade now!

Ready to get started with anonymous questions today? It's easy! Learn more.

Question has a verified solution.

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

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Suggested Courses
Course of the Month9 days, 11 hours left to enroll

762 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