简体   繁体   English

拆分一个字符串,得到倒数第二个字

[英]Split a string and get the second last word

I have a string "Hai,Hello,How,are,you" 我有一个字符串“Hai,你好,怎么样,是,你”

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. 我没有得到倒数第二个字。

What you need is String lastWord = bits[bits.length-2]; 你需要的是String lastWord = bits[bits.length-2]; because bits[bits.length-1]; 因为bits[bits.length-1]; will return you the last word and not the second last. 将返回最后一个字而不是最后一个字。

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

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. 试试它会起作用。

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM