【发布时间】: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);