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

后端 未结 13 2102
小蘑菇
小蘑菇 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:07

    The simple one I used to do is

    str.contains(" ") ? str.split(" ")[0] : str
    

    Where str is your string or text bla bla :). So, if

    1. str is having empty value it returns as it is.
    2. str is having one word, it returns as it is.
    3. str is multiple words, it extract the first word and return.

    Hope this is helpful.

提交回复
热议问题