Reputation: 4442
In Java we have indexOf
and lastIndexOf
. Is there anything like lastSubstring
? It should work like :
"aaple".lastSubstring(0, 1) = "e";
Upvotes: 4
Views: 33870
Reputation: 7092
For those looking to get a substring after some ending delimiter, e.g. parsing file.txt
out of /some/directory/structure/file.txt
I found this helpful: StringUtils.substringAfterLast
public static String substringAfterLast(String str,
String separator)
Gets the substring after the last occurrence of a separator. The separator is not returned.
A null string input will return null. An empty ("") string input will return the empty string. An empty or null separator will return the empty string if the input string is not null.
If nothing is found, the empty string is returned.
StringUtils.substringAfterLast(null, *) = null
StringUtils.substringAfterLast("", *) = ""
StringUtils.substringAfterLast(*, "") = ""
StringUtils.substringAfterLast(*, null) = ""
StringUtils.substringAfterLast("abc", "a") = "bc"
StringUtils.substringAfterLast("abcba", "b") = "a"
StringUtils.substringAfterLast("abc", "c") = ""
StringUtils.substringAfterLast("a", "a") = ""
StringUtils.substringAfterLast("a", "z") = ""
Upvotes: 0
Reputation: 9110
Not in the standard Java API, but ...
Apache Commons has a lot of handy String helper methods in StringUtils
... including StringUtils.right("apple",1)
just grab a copy of commons-lang.jar from commons.apache.org
Upvotes: 11
Reputation: 22456
Generalizing the other responses, you can implement lastSubstring as follows:
s.substring(s.length()-endIndex,s.length()-beginIndex);
Upvotes: 4
Reputation: 38297
I'm not aware of that sort of counterpart to substring()
, but it's not really necessary. You can't efficiently find the last index with a given value using indexOf()
, so lastIndexOf()
is necessary. To get what you're trying to do with lastSubstring()
, you can efficiently use substring()
.
String str = "aaple";
str.substring(str.length() - 2, str.length() - 1).equals("e");
So, there's not really any need for lastSubstring()
.
Upvotes: -1
Reputation: 11037
Wouldn't that just be
String string = "aaple";
string.subString(string.length() - 1, string.length());
?
Upvotes: 0