Tom
Tom

Reputation: 845

In Java String, How to cut a part of a String by just 1 line of code (probally use Regex)?

given this string http://verylongurlverylonngurl/image.jpg & I wanna cut all the part before the last "/". For example, I wanna remove the part http://verylongurlverylonngurl/ of the string above. The result will be "image.jpg".

I have to cut the String "Label" & the code to cut that String must be inside the super() keyword & super keyword must be the first statement in the constructor. Loook at this code:

private class TextShortenedCheckBox extends CheckBox{
      private String originalText;
       public TextShortenedCheckBox(String label, int visibleLength){
            super(label.substring(label.length()-9,label.length()-1));


            originalText=label;

       }
       @Override
       public String getText(){
          return originalText;
       }
    }

Look at the code: label.substring(label.length()-9,label.length()-1) this code give the result but not be able to apply for other variable string.

So, how to cut a part of a String by just 1 line of code, so that I can put that code inside super(). Maybe we have to use Regex or something?

Upvotes: 0

Views: 1460

Answers (3)

rajesh
rajesh

Reputation: 3407

You can use lastIndexOf('/')

Returns the index within this string of the last occurrence of the specified character. For values of ch in the range from 0 to 0xFFFF (inclusive), the index (in Unicode code units) returned is the largest value k such that: this.charAt(k) == ch is true. For other values of ch, it is the largest value k such that: this.codePointAt(k) == ch is true. In either case, if no such character occurs in this string, then -1 is returned. The String is searched backwards starting at the last character.

Upvotes: 1

Achintya Jha
Achintya Jha

Reputation: 12843

Try this:

String str ="http://verylongurlverylonngurl/image.jpg";
str = str.substring(str.lastIndexOf("/")+1);
System.out.println(str);

Output:

image.jpg

Upvotes: 1

jlordo
jlordo

Reputation: 37813

What about

str = str.substring(str.lastIndexOf("/") + 1);

Upvotes: 5

Related Questions