Easy question about breaking apart strings

In PHP there is a function to explode a string to where if there is white space it will break each word out into an array.  How would I do that in java?

So say I have a string come in with "red condor fly" and I need to get "red" "condor" "fly" how would I get those three words seperated, or actually x number of words.
filament90Asked:
Who is Participating?
 
zzynxConnect With a Mentor Software engineerCommented:
String parts[] = "red condor fly".split("\\s+");
0
 
zzynxSoftware engineerCommented:
use split()
0
 
CEHJCommented:
String[] tokens = s.split(" ");
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
zzynxSoftware engineerCommented:
If you have the string "red   condor fly"
with
>> String[] tokens = s.split(" ");
You'll have
- tokens[0] = "red"
- tokens[1] = ""
- tokens[2] = ""
- tokens[3] = "condor"
- tokens[4] = "fly"

with

>> String parts[] = s.split("\\s+");
you'll have
- parts[0] = "red"
- parts[1] = "condor"
- parts[2] = "fly"


0
 
zzynxSoftware engineerCommented:
Remark: split() is available since 1.4
0
 
CEHJCommented:
No you won't have that with split(" ") ;-)
0
 
cyberdevil67Commented:
Hi filament90,

 As everyone else has said but here is more info on the subject http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html

Cheers!
0
 
CEHJCommented:
If you're unfortunate enough to be stuck with Java < 1.4 then use java.util.StringTokenizer
0
 
zzynxSoftware engineerCommented:
Well, I just tested...

        String tokens[] = "red   condor fly".split(" ");
        for (int i=0; i<tokens.length; i++)
            System.out.println("<" + tokens[i] + ">");

prints out:

<red>
<>
<>
<condor>
<fly>
0
 
CEHJCommented:
On my machine:

System.out.println("red condor fly".split(" ").length);

prints

3
0
 
CEHJCommented:
I see what you're saying. If you have unequal spaces, yes.
0
 
CEHJCommented:
(and you want that fact to be ignored)
0
 
zzynxSoftware engineerCommented:
Thanks for accepting, flament90

>> I see what you're saying. If you have unequal spaces, yes.
>> (and you want that fact to be ignored)
Exactly ;°)
0
All Courses

From novice to tech pro — start learning today.