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

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

    The second parameter of the split method is optional, and if specified will split the target string only N times.

    For example:

    String mystring = "the quick brown fox";
    String arr[] = mystring.split(" ", 2);
    
    String firstWord = arr[0];   //the
    String theRest = arr[1];     //quick brown fox
    

    Alternatively you could use the substring method of String.

提交回复
热议问题