Trim a string in java to get first word

java

Solution

  String firstWord = "Magic Word";
     if(firstWord.contains(" ")){
        firstWord= firstWord.substring(0, firstWord.indexOf(" ")); 
        System.out.println(firstWord);
     }

Problem

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?

Original source

Related problems