Krishna Suthar
Krishna Suthar

Reputation: 3075

Remove string after last occurrence of a character

In my application, I am appending a string to create path to generate a URL. Now I want to remove that appended string on pressing back button.

Suppose this is the string:

/String1/String2/String3/String4/String5

Now I want a string like this:

/String1/String2/String3/String4/

How can I do this?

Upvotes: 44

Views: 71383

Answers (5)

ccpizza
ccpizza

Reputation: 31666

You can use org.apache.commons.lang3.StringUtils.substringBeforeLast which is null-safe.

From the javadoc:

// The symbol * is used to indicate any input including null.
StringUtils.substringBeforeLast(null, *)      = null
StringUtils.substringBeforeLast("", *)        = ""
StringUtils.substringBeforeLast("abcba", "b") = "abc"
StringUtils.substringBeforeLast("abc", "c")   = "ab"
StringUtils.substringBeforeLast("a", "a")     = ""
StringUtils.substringBeforeLast("a", "z")     = "a"
StringUtils.substringBeforeLast("a", null)    = "a"
StringUtils.substringBeforeLast("a", "")      = "a"

Maven dependency:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.8</version>
</dependency>

Upvotes: 7

rsan
rsan

Reputation: 1887

String whatyouaresearching = myString.substring(0, myString.lastIndexOf("/"))

Upvotes: 49

huskygrad
huskygrad

Reputation: 1397

The third line in Nepster's answer should be

String x =path.substring(pos+1 , path.length());

and not String x =path.substring(pos+1 , path.length()-1); since substring() method takes the end+1 offset as the second parameter.

Upvotes: 0

Zar E Ahmer
Zar E Ahmer

Reputation: 34360

Easiest way is ...

        String path = "http://zareahmer.com/questions/anystring";

        int pos = path.lastIndexOf("/");

        String x =path.substring(pos+1 , path.length()-1);

now x has the value stringAfterlastOccurence

Upvotes: 3

Dheeresh Singh
Dheeresh Singh

Reputation: 15701

You can use lastIndexOf() method for same with

if (null != str && str.length() > 0 )
{
    int endIndex = str.lastIndexOf("/");
    if (endIndex != -1)  
    {
        String newstr = str.substring(0, endIndex); // not forgot to put check if(endIndex != -1)
    }
}  

Upvotes: 70

Related Questions