CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jan 2010
    Posts
    161

    Use string contains for multiple checks

    Hi everyone

    I wanted to know wether is possible to use the contains method to check multiple values.

    For example:

    If I want to know wether a string contains a "?" or "!". How would I change the syntax to accomodate both?

    I am currenly using this : value.contains("?"); but I want to be able to put multiple characters check.

    Thank you

  2. #2
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: Use string contains for multiple checks

    You could use:
    Code:
    if ( value.contains("?") || value.contains("!") ) {...}
    Or you could use a regex Matcher.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  3. #3
    Join Date
    Jan 2010
    Posts
    161

    Re: Use string contains for multiple checks

    I was aware of that syntax where I can use "||" or "&&" to add multiple values but it's not neat and effective when you want to check multiple values as your repeating the same line of code again and again.

    I never came accross a regex matcher, can you provide an example of how that would work with the two symbols I've mentioned?

    Thank you

  4. #4
    Join Date
    Nov 2006
    Location
    Barcelona - Catalonia
    Posts
    364

    Re: Use string contains for multiple checks

    Something like this should work:
    Code:
    Pattern p = Pattern.compile("[?!]");
    Matcher m = p.matcher(value);
    
    if (m.find()) {
    	System.out.println("value = " + value + " matches");
    }
    else {
    	System.out.println("value = " + value + " does NOT match");
    }
    Another solution could be:
    Code:
    if (value.matches(".*[?!].*")) {
    	System.out.println("value = " + value + " matches");
    }
    else {
    	System.out.println("value = " + value + " does NOT match");
    }
    Albert.
    Last edited by AlbertGM; August 10th, 2012 at 07:27 AM.
    Please, correct me. I'm just learning.... and sorry for my english :-)

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured