【问题标题】:extract a substring from the end of a string until the First space is encountered?从字符串末尾提取子字符串,直到遇到第一个空格?
【发布时间】:2014-01-04 04:08:47
【问题描述】:

我有一个这样的字符串:

"De Proost Wim"

我需要"De Proost" 在一个字符串中,"Wim" 在另一个

所以我需要从字符串末尾开始的第一个 ' '

【问题讨论】:

  • 您可以将lastIndexOf(' ')substring 方法一起使用。
  • 我希望你不要假设人们的名字不包含空格。那将是一个错误。

标签: java android substring space


【解决方案1】:

您可以将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。

【讨论】:

    【解决方案2】:
    String str = /*Your-String*/;
    String[] subs = str.split(" ");
    String strLast = "";
    if( subs.length > 1 )
        strLast = subs[subs.length-1];
    

    【讨论】:

    • 你不会在第一个字符串中得到“De Proost”。您将不得不重新连接它们。
    • @ZouZou 您可以将字符串缓冲区与数组中的其余元素附加在一起。
    • 是的,但是对于这样一个简单的任务来说,这太过分了。使用substringlastIndexOf 2 行就足够了。
    • 同意.. str.lastIndexOf(" ");更好。
    【解决方案3】:

    也许您可以尝试以下方法:

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

    用法:

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

    每个索引处的值:

    0: "De Proost"

    1: "Wim"

    【讨论】:

      猜你喜欢
      • 2015-12-14
      • 2011-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-26
      • 2020-02-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多