parsing a string
If I have a string that has a value of:
How can I get just "test-page" out of that string? I don't want anything before or after that.
Use lastIndexOf to get positions of / and ? and substring it
String str = "/page/subpage/test-page?p_id=";
int slashPos = str.lastIndexOf("/");
int steps = str.lastIndexOf("?");
String testPage = str.substring(slashPos+1, steps);
There will be situations where there is no query string, and when testing the code, i am gettting a StringIndexOutOfBounds exception when the url does not have a ?. How can I solve this?
If lasIndexOf cant find the value it's looking for it'll return -1.
So use a if statement for the substring if steps > 0 use str.substring(slashPos+1, steps);
If it's even more complicated than this, maybe you should use regex
yeah, that's actually what I did and it seems to be working fine.
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)