开发者

Last substring of string

开发者 https://www.devze.com 2022-12-29 07:52 出处:网络
In Java we have index开发者_运维技巧Of and lastIndexOf. Is there anything like lastSubstring? Itshould work like :

In Java we have index开发者_运维技巧Of 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)

http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html#right(java.lang.String,%20int)

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


Perhaps lasIndexOf(String) ?


Wouldn't that just be

String string = "aaple";
string.subString(string.length() - 1, string.length());

?


You can use String.length() and String.length() - 1


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().

0

精彩评论

暂无评论...
验证码 换一张
取 消