In Java we have indexOf
and lastIndexOf
. Is there anything like lastSubstring
? It should work like :
"aaple".lastSubstring(0, 1) = "e";
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
Generalizing the other responses, you can implement lastSubstring as follows:
s.substring(s.length()-endIndex,s.length()-beginIndex);
Wouldn't that just be
String string = "aaple";
string.subString(string.length() - 1, string.length());
?
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") = ""
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()
.
substring(...)
creates a new string so ==
will always return false. Only String literals inside .java files are pooled and re-used. The boolean x for the snippet String a = "foo"; String b = "foo"; boolean x = a == b;
will be true
.
May 4, 2010 at 21:17
0
and1
represent? And do you mean thate
is returned?indexOf
andlastIndexOf
both take a string and find it without the main string, returning the location. You seem to be describing the opposite; you want a version ofsubstring()
that counts from the end instead of the beginning