Last substring of string
For those who want to get a substring after some trailing delimiter, eg. parsing file.txt
from/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") = ""
a source to share
I do not know of this kind substring()
, but it is not necessary. You cannot efficiently find the last index with a given value with indexOf()
, so lastIndexOf()
it is necessary. To get what you are trying to do with lastSubstring()
, you can use effectively substring()
.
String str = "aaple";
str.substring(str.length() - 2, str.length() - 1).equals("e");
So there is no need for lastSubstring()
.
a source to share