java 拆分字符串并获取倒数第二个单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36402287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split a string and get the second last word
提问by Jocheved
I have a string "Hai,Hello,How,are,you"
我有一个字符串“Hai,Hello,How,are,you”
What I needed is I need the second last word that is "are"
我需要的是我需要倒数第二个词“是”
String string = "Hai,Hello,How,are,you";
String[] bits = string.split(",");
String lastWord = bits[bits.length-1]
tvs.setText(lastWord);
But when I did like this:
但是当我这样做时:
String lastWord = bits[bits.length-2];
I am not getting the second last word.
我没有得到倒数第二个字。
回答by user2004685
What you need is String lastWord = bits[bits.length-2];
because bits[bits.length-1];
will return you the last word and not the second last.
您需要的是String lastWord = bits[bits.length-2];
因为bits[bits.length-1];
将返回最后一个词而不是倒数第二个词。
This is because indexing of array starts with 0
and ends in length-1
.
这是因为数组的索引0
以length-1
.
Here is the updated code snippet:
这是更新后的代码片段:
String string = "Hai,Hello,How,are,you";
String[] bits = string.split(",");
String lastWord = bits[bits.length - 2];
tvs.setText(lastWord);
回答by Amit Gupta
Here first you have to find out index of character ',' from last. And after that second character ',' from the last. After that you can find out sub string between them .
首先,您必须从最后找出字符 ',' 的索引。在第二个字符 ',' 之后。之后,您可以找出它们之间的子字符串。
String string = "Hai,Hello,How,are,you";
int lastIndex,secondLastIndex;
lastIndex=string.lastIndexOf(',');
secondLastIndex=string.lastIndexOf(',',lastIndex-1);
System.out.println(string.substring(secondLastIndex+1,lastIndex));
try it will work.
尝试它会起作用。
回答by nariuji
I'm not sure but I think like this.
我不确定,但我是这样想的。
if your code is as follows, it does not work.
如果您的代码如下,则它不起作用。
String string = "Hai,Hello,How,are,";
String[] bits = string.split(",");
↓
bits[]…{ "Hai","Hello","How","are" }
bits[bits.length-2]…"How"
This code works.
此代码有效。
String string = "Hai,Hello,How,are,";
String[] bits = string.split(",", -1);
↓
bits[]…{ "Hai","Hello","How","are","" }
bits[bits.length-2]…"are"