Trim a string in java to get first word
You could use String
's replaceAll()
method which takes a regular expression as input, to replace everything after the space including the space, if a space does indeed exist, with the empty string:
String firstWord = sentence.replaceAll(" .*", "");
String firstWord = "Magic Word";
if(firstWord.contains(" ")){
firstWord= firstWord.substring(0, firstWord.indexOf(" "));
System.out.println(firstWord);
}