Trim a string in java to get first word

Viewed 102482

I have a String "Magic Word". I need to trim the string to extract "Magic" only. I am doing the following code.

String sentence = "Magic Word";  
String[] words = sentence.split(" ");  

for (String word : words)  
{  
   System.out.println(word);  
}  

I need only the first word. Is there any other methods to trim a string to get first word only if space occurs?

8 Answers

We should never make simple things more complicated. Programming is about making complicated things simple.

string.split(" ")[0]; //the first word.

Related