我有一个这样的字符串:从字符串的末尾提取子字符串,直到遇到第一个空格为止?
"De Proost Wim"
,我需要在一个字符串"De Proost"
和"Wim"
在另一个
,所以我需要第一' '
开始在字符串的结尾。
我有一个这样的字符串:从字符串的末尾提取子字符串,直到遇到第一个空格为止?
"De Proost Wim"
,我需要在一个字符串"De Proost"
和"Wim"
在另一个
,所以我需要第一' '
开始在字符串的结尾。
String str = /*Your-String*/;
String[] subs = str.split(" ");
String strLast = "";
if(subs.length > 1)
strLast = subs[subs.length-1];
你不会在第一个字符串中得到“De Proost”。你将不得不调和他们。 –
@ZouZou你可以在数组中添加一个字符串缓冲区和剩余的元素。 –
是的,但这对于这样一个简单的任务来说是非常矫枉过正的。使用'substring'和'lastIndexOf'就足够了2行。 –
或许你可以尝试像:
public static String[] extract(final String string){
assert string != null;
final int i = string.lastIndexOf(' ');
if(i == -1)
return new String[]{string};
final String first = string.substring(0, i);
final String last = string.substring(i+1);
return new String[]{first, last};
}
用法:
0: "De Proost"
0123:各指标在
final String[] parts = extract("De Proost Wim");
价值
您可以使用lastIndexOf(' ')
与substring
方法:
String s = "De Proost Wim";
int lastIndex = s.lastIndexOf(' ');
String s1 = s.substring(0, lastIndex);
String s2 = s.substring(lastIndex+1);
System.out.println(s1); //De Proost
System.out.println(s2); //Wim
只要确保lastIndexOf
不返回-1。
你可以使用'substring'方法'lastIndexOf('')'。 –
我希望你不要假设人的名字不包含空格。那将是一个错误。 –