Ajinkya
Ajinkya

Reputation: 22710

Substring in Java

I have a string in format /remove_this/I_want_this_onward/any_number_of_characters.
I want to remove /remove_this and want to get remaining string i.e. /I_want_this_onward/any_number_of_characters.
Ex. Input String /myApp/home/welcome , I want to extract /home/welcome.
What will be the the easiest way in Java to get it done ?

EDIT: (extracted from comments)

I want it to extract /home/welcome from redirect:/myapp/home/welcome.

Upvotes: 0

Views: 1034

Answers (3)

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51445

Assuming your comment in Daniel's answer is the last word, I'm guessing you wish to find the second forward slash, and copy the remaining characters.

Here's my attempt.

int pos = s.indexOf("/");
s.substring(s.indexOf("/", pos+1));

if you wish to find the third forward slash, you'd add the following line in between the two lines of code above:

pos = s.indexOf("/", pos+1);

if you wish to find the fourth, fifth, sixth, etc. forward slash, you would put the above statement in a WHILE loop, in between the two lines of code above.

Upvotes: 3

sdolgy
sdolgy

Reputation: 7001

 yourString.replace(aOldPattern, aNewPattern);

http://www.javapractices.com/topic/TopicAction.do?Id=80

This is assuming you know what the string is you want to replace each time. If you don't, you can use:

 yourString.split("/"); // if you know the delimiter is always `/`

From that, you can then omit the first instance from the split and print out the rest...

Upvotes: 1

Daniel
Daniel

Reputation: 28074

That would be

s.substring(s.indexOf("/",1))

Upvotes: 7

Related Questions