www.webdeveloper.com
Results 1 to 6 of 6

Thread: parsing a string

  1. #1
    Join Date
    Jan 2003
    Location
    PA
    Posts
    1,898

    parsing a string

    If I have a string that has a value of:

    /page/subpage/test-page?p_id=...

    How can I get just "test-page" out of that string? I don't want anything before or after that.

    Thanks!

  2. #2
    Join Date
    Jan 2011
    Posts
    10
    Use lastIndexOf to get positions of / and ? and substring it

    Code:
    String str = "/page/subpage/test-page?p_id=";
    
            int slashPos = str.lastIndexOf("/");
            int steps    = str.lastIndexOf("?");
    
            String testPage = str.substring(slashPos+1, steps);
            System.out.println(testPage);

  3. #3
    Join Date
    Jan 2003
    Location
    PA
    Posts
    1,898
    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?

    Thanks!!!

  4. #4
    Join Date
    Jan 2011
    Posts
    10
    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);
    else str.substring(slashPos+1);

    If it's even more complicated than this, maybe you should use regex

  5. #5
    Join Date
    Jan 2003
    Location
    PA
    Posts
    1,898
    yeah, that's actually what I did and it seems to be working fine.

    Thanks!!!

  6. #6
    Join Date
    Jan 2011
    Posts
    10
    Nice

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles