尝试编写一个简短的方法,以便我可以解析一个字符串并提取第一个单词.我一直在寻找最好的方法来做到这一点.
我假设我会使用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)
或者,您可以使用String的substring
方法.
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)
以上是执行此任务的最快方法.
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 :) 在哪里.所以,如果
str
具有空值,它返回原样.str
有一个单词,它会按原样返回.str
是多个单词,它提取第一个单词并返回.希望这是有帮助的.
您可以使用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)
split
import org.apache.commons.lang3.StringUtils;
...
StringUtils.substringBefore("Grigory Kislin", " ")
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
138534 次 |
最近记录: |