Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 225
  • Last Modified:

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.
0
filament90
Asked:
filament90
  • 6
  • 6
1 Solution
 
zzynxSoftware engineerCommented:
use split()
0
 
CEHJCommented:
String[] tokens = s.split(" ");
0
 
zzynxSoftware engineerCommented:
String parts[] = "red condor fly".split("\\s+");
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 6
  • 6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now