javaguy
javaguy

Reputation: 4442

Last substring of string

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

Answers (7)

Ryan Walls
Ryan Walls

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

laher
laher

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)

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

Upvotes: 11

Eyal Schneider
Eyal Schneider

Reputation: 22456

Generalizing the other responses, you can implement lastSubstring as follows:

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

Upvotes: 4

Jonathan M Davis
Jonathan M Davis

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

Istao
Istao

Reputation: 7585

Perhaps lasIndexOf(String) ?

Upvotes: 3

vinaynag
vinaynag

Reputation: 271

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

Upvotes: 0

ILMTitan
ILMTitan

Reputation: 11037

Wouldn't that just be

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

?

Upvotes: 0

Related Questions