简体   繁体   English

从字符串末尾提取子字符串,直到遇到第一个空格?

[英]extract a substring from the end of a string until the First space is encountered?

I have a string like this: 我有一个像这样的字符串:

"De Proost Wim"

And i need "De Proost" in a string and "Wim" in another 我需要在字符串中输入"De Proost" ,在另一个字符串中输入"Wim"

so i need the first ' ' starting at the end of a string. 所以我需要第一个' '从字符串的末尾开始。

String str = /*Your-String*/;
String[] subs = str.split(" ");
String strLast = "";
if( subs.length > 1 )
    strLast = subs[subs.length-1];

Perhaps you could try something like: 也许您可以尝试类似的方法:

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};
}

Usage: 用法:

final String[] parts = extract("De Proost Wim");

Value at each index: 每个索引的值:

0: "De Proost"

1: "Wim"

You can use lastIndexOf(' ') with the substring method : 您可以将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

Just make sure that lastIndexOf doesn't return -1. 只要确保lastIndexOf不返回-1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM