Last substring of string

Java has indexOf

and lastIndexOf

. Is there something like lastSubstring

? It should work like this:

"aaple".lastSubstring(0, 1) = "e";

      

+2


a source to share


7 replies


Not in the standard Java API, but ...

Apache Commons has many useful 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

+11


a source


Summarizing the other answers, you can implement lastSubstring like this:



s.substring(s.length()-endIndex,s.length()-beginIndex);

      

+3


a source


+2


a source


It wouldn't be easy

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

      

?

0


a source


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

0


a source


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")     = ""

      

0


a source


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

.

-1


a source







All Articles