获取java中的分割长度

时间:2018-03-01 11:30:32

标签: java split

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

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

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

例如,当我从网页上获取数据时,我现在的价值不是。

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

答案 2 :(得分:-1)

另一种方法是避免分裂并直接删除最后一个单词。

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

这样,你从最后一个空格到字符串结束