What is the best way to extract the first word from a string in Java?

后端 未结 13 2092
小蘑菇
小蘑菇 2020-11-29 02:38

Trying to write a short method so that I can parse a string and extract the first word. I have been looking for the best way to do this.

I assume I would use s

13条回答
  •  迷失自我
    2020-11-29 03:12

    To simplify the above:

    text.substring(0, text.indexOf(' ')); 
    

    Here is a ready function:

    private String getFirstWord(String text) {
    
      int index = text.indexOf(' ');
    
      if (index > -1) { // Check if there is more than one word.
    
        return text.substring(0, index).trim(); // Extract first word.
    
      } else {
    
        return text; // Text is the first word itself.
      }
    }
    

提交回复
热议问题