【问题标题】:Get Length of split in java [duplicate]在java中获取拆分长度[重复]
【发布时间】:2018-08-09 11:13:16
【问题描述】:

有一个字符串,我用空格分割它,我想得到最后一个。

String test = "Hey Hi Hello"; // Defining "test" String
test = test.split(" ")[2]; // Now "test" is "Hello"
System.out.print(test); // prints Hello

我应该这样做以获得“test”字符串的最后一个单词。但我知道字符串的长度。如果我知道字符串的长度怎么办?我应该在[ ] 之间写什么才能得到最后的结果?

例如,当我从网页获取数据时,我现在不知道该值是什么。

【问题讨论】:

  • temp = test.split(" ");测试 = temp[temp.length - 1]; ?
  • 这是一种非常低效的方法。更好的方法是test = test.substring(test.lastIndexOf(" ") + 1);

标签: java split


【解决方案1】:

test.split 返回Strings 的数组。只需将其保存在某处而不是立即使用它并检查其length

String test = "Hey Hi Hello";
String[] words = test.split(" ");
test = words[words.length - 1];
System.out.print(test);

【讨论】:

    【解决方案2】:
    String[] temp = test.split(" "); //this will split whole string into array using white space.
    test = temp[temp.length-1]; //gets the element at the last index of temp array
    

    【讨论】:

      【解决方案3】:

      另一种方法是避免拆分,直接将最后一个单词剪掉。

      String text = "One Two Three";
      text = text.substring(text.lastIndexOf(" ") + 1);
      

      这样,你将字符串从最后一个空格取出到字符串的末尾

      【讨论】:

        猜你喜欢
        • 2012-10-30
        • 2011-05-05
        • 2016-04-02
        • 1970-01-01
        • 2013-11-18
        • 1970-01-01
        • 1970-01-01
        • 2011-07-04
        • 2018-04-19
        相关资源
        最近更新 更多