Remove string after last occurrence of a character

前端 未结 5 2071
慢半拍i
慢半拍i 2020-12-01 07:41

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 s

相关标签:
5条回答
  • 2020-12-01 07:57

    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.

    0 讨论(0)
  • 2020-12-01 07:59
    String whatyouaresearching = myString.substring(0, myString.lastIndexOf("/"))
    
    0 讨论(0)
  • 2020-12-01 08:00

    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>
    
    0 讨论(0)
  • 2020-12-01 08:05

    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)
        }
    }  
    
    0 讨论(0)
  • 2020-12-01 08:12

    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

    0 讨论(0)
提交回复
热议问题