4

HI Everyone. I'm sorry for this embarrassingly newbie question but I cannot seem to figure out the command to do it. I'm okay with python and had a script in jython that I'm convering to pure java(and learning along the way).

I have a string: Java is really cool

I know how to strip the string to get the final result: really cool

but i'm not sure the command to do it in java. I found commands in java to do it specifically by text but I want to use a space as a deliminator and get the words.

Can someone tell me what java command to use? I would want to be able either remove the first two words and/or specifically select the words I want.

Thanks,

Lostsoul
  • 25,013
  • 48
  • 144
  • 239
  • What are the rules that would decide which words to extract? Without rules there is no code. Otherwise String#split(...) allows you to split Strings based on most any delimiter. – Hovercraft Full Of Eels Apr 26 '11 at 01:55

3 Answers3

8

I think you are looking for String.split.

String s = "Java is really cool";
String words[] = s.split(" ");
String firstTwo = words[0] + "  " + words[1]; // first two words
String lastTwo = words[words.length - 2] + " "
        + words[words.length - 1]; // last two words
mellamokb
  • 56,094
  • 12
  • 110
  • 136
  • Thanks, looks good. I was able to get this far but how do I get everything from the second words onwards..in python it would be words[2:] but not sure how to do it in java. – Lostsoul Apr 26 '11 at 02:04
  • 1
    @Lostsoul: Might just have to create a new array, and use a good-ol' `for` loop to grab words from 2 onward. words[2:] is just syntactic sugar for the same. – mellamokb Apr 26 '11 at 02:20
2

Please take a look at String.split method

denis.solonenko
  • 11,645
  • 2
  • 28
  • 23
2
String foo = "java is really cool";
String bar[] = foo.split(" ");

this will separate all of the words into an array.

mellamokb
  • 56,094
  • 12
  • 110
  • 136
Sam
  • 1,741
  • 5
  • 18
  • 22