从Java中的字符串中提取第一个单词的最佳方法是什么?

use*_*033 54 java string

尝试编写一个简短的方法,以便我可以解析一个字符串并提取第一个单词.我一直在寻找最好的方法来做到这一点.

我假设我会使用str.split(","),但是我想从字符串中抓取第一个第一个单词,并将其保存在一个变量中,并将其余的标记放在另一个变量中.

这样做有简洁的方法吗?

Joh*_*erg 92

split方法的第二个参数是可选的,如果指定将仅分割目标字符串的N次数.

例如:

String mystring = "the quick brown fox";
String arr[] = mystring.split(" ", 2);

String firstWord = arr[0];   //the
String theRest = arr[1];     //quick brown fox
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用Stringsubstring方法.

  • 这还不够强大.假设句子是"Hello,quick brown fox",那么你得到的第一个单词将是"Hello",而不是"Hello".仅按空间拆分并不总能获得所需的结果.String firstWord = mystring.split("[\\ t \\n \\,\\?\\; \\.\\:\\!]")[0]; 这将涵盖更多选项. (5认同)
  • 拆分工作,但绝对是一个基于RegEx的解决方案,它有自己的性能惩罚. (4认同)
  • 很好,但更简洁:String firstWord = mystring.split("",2)[0]; 如果你只需要第一个字. (3认同)

ada*_*shr 43

你应该这样做

String input = "hello world, this is a line of text";

int i = input.indexOf(' ');
String word = input.substring(0, i);
String rest = input.substring(i);
Run Code Online (Sandbox Code Playgroud)

以上是执行此任务的最快方法.

  • 如果字符串上没有任何空格,请确保添加一个检查. (6认同)

Zon*_*Zon 35

为简化上述内容:

text.substring(0, text.indexOf(' ')); 
Run Code Online (Sandbox Code Playgroud)

这是一个准备好的功能:

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.
  }
}
Run Code Online (Sandbox Code Playgroud)


Mad*_*ota 13

我以前做的简单就是

str.contains(" ") ? str.split(" ")[0] : str
Run Code Online (Sandbox Code Playgroud)

str你的字符串或文字bla bla :) 在哪里.所以,如果

  1. str 具有空值,它返回原样.
  2. str 有一个单词,它会按原样返回.
  3. str 是多个单词,它提取第一个单词并返回.

希望这是有帮助的.


mik*_*iku 6

您可以使用String.split限制为2.

    String s = "Hello World, I'm the rest.";
    String[] result = s.split(" ", 2);
    String first = result[0];
    String rest = result[1];
    System.out.println("First: " + first);
    System.out.println("Rest: " + rest);

    // prints =>
    // First: Hello
    // Rest: World, I'm the rest.
Run Code Online (Sandbox Code Playgroud)


GKi*_*lin 5

import org.apache.commons.lang3.StringUtils;

...
StringUtils.substringBefore("Grigory Kislin", " ")
Run Code Online (Sandbox Code Playgroud)

  • 这是最好的答案,因为它可以在一行上完成并且不使用数组。它正确处理空值等。 (2认同)