You could use lastIndexOf() method on String
String last = string.substring(string.lastIndexOf('-') + 1);
Answer from Denis Bazhenov on Stack OverflowYou could use lastIndexOf() method on String
String last = string.substring(string.lastIndexOf('-') + 1);
Save the array in a local variable and use the array's length field to find its length. Subtract one to account for it being 0-based:
String[] bits = one.split("-");
String lastOne = bits[bits.length-1];
Caveat emptor: if the original string is composed of only the separator, for example "-" or "---", bits.length will be 0 and this will throw an ArrayIndexOutOfBoundsException. Example: https://onlinegdb.com/r1M-TJkZ8
Another way to get the last token/word
String lastToken = sentance.replaceAll(".* ", "");
You only need to split it once, and take the last element.
String sentence = "Any simpler way to get the last element of a Java array?";
String[] tokens = sentence.split(" ");
String lastToken = tokens[tokens.length-1];
It's awkward, but there's really no other way to do it unless you have foreknowledge of the length of the string.
Edit: this one is simplier:
=REGEXEXTRACT(A1,"[^/]+$")
You could use this formula:
=REGEXEXTRACT(A1,"(?:.*/)(.*)$")
And also possible to use it as ArrayFormula:
=ARRAYFORMULA(REGEXEXTRACT(A1:A3,"(?:.*/)(.*)$"))
Here's some more info:
- the RegExExtract function
- Some good examples of syntax
- my personal list of Regex Tricks
This formula will do the same:
=INDEX(SPLIT(A1,"/"),LEN(A1)-len(SUBSTITUTE(A1,"/","")))
But it takes A1 three times, which is not prefferable.
You could do this too
=index(SPLIT(A1, "/"), COLUMNS(SPLIT(A1, "/"))-1)