SitePoint Sponsor

User Tag List

Results 1 to 7 of 7
  1. #1
    SitePoint Zealot
    Join Date
    Mar 2006
    Posts
    144
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    check if a string has a specific character

    hey guys.

    i want to check if a string contain "/" using an if-else statement.

    what's the method to accomplish this?

  2. #2
    SitePoint Wizard rozner's Avatar
    Join Date
    Oct 2002
    Location
    Paris
    Posts
    1,058
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    several ways to do this, easiest would be something like:

    Code:
    String string = "whatever";
    
    if (string.lastIndexOf('/') >=0){
    // it contains it
    } else {
    // it does not contain it
    }

  3. #3
    SitePoint Evangelist borna's Avatar
    Join Date
    Jun 2006
    Location
    Iran, Tehran
    Posts
    475
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    why lastIndexOf(), why not indexOf('/') ?
    -1/2=999?

  4. #4
    SitePoint Wizard rozner's Avatar
    Join Date
    Oct 2002
    Location
    Paris
    Posts
    1,058
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    that could work just as well, as I said there are several ways to do this, personally I would use:

    Code:
    string.matches("\\x2f");
    They'll all work just as well.

  5. #5
    SitePoint Wizard silver trophy rushiku's Avatar
    Join Date
    Dec 2003
    Location
    A van down by the river
    Posts
    2,056
    Mentioned
    0 Post(s)
    Tagged
    1 Thread(s)
    string.matches("\\x2f");

    This will only work if "/".equals( "\\x2f" ) is true
    I'm not addressing whether or not the character code \x2f is the same as /, I'm addressing that the string must be / and nothing else.

    eg: "path/file.txt".matches( "\\x2f" ) is false.

    (I thought it was a neat usage of matches() and had to try it)

    In 1.5, String has the new contains method:

    "path/file.txt".contains( "/" )

  6. #6
    SitePoint Wizard rozner's Avatar
    Join Date
    Oct 2002
    Location
    Paris
    Posts
    1,058
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    good point, I think this might work though, untested

    string.matches(".*\\x2f.*);

    I guess "contains" would be the best use, strangely I never noticed that method, and I've been using Java 5 for a while

  7. #7
    SitePoint Zealot xzyfer's Avatar
    Join Date
    Mar 2004
    Location
    oz
    Posts
    99
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    theres always

    string.conatins('/'):

    in J2SE anyway


Bookmarks

Posting Permissions

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