Results 1 to 5 of 5
  1. #1
    Tman is offline Member
    Join Date
    Apr 2012
    Posts
    4
    Rep Power
    0

    Default Using Placeholders such as * and ? in a String

    I'm trying to test whether a string contains 3 "a"s. The way I first thought of doing this was to test it using something like string.equal(* + "a" + * + "a" + * + "a" + *); as I thought the * would count as "anything". It doesn't seem to be the case however. Is there any other way to execute such a test?

    Thanks in advance!

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Using Placeholders such as * and ? in a String

    String has an indexOf() method that will do this. (without resorting to placeholders)

    [Edit] Just reread more carefully... indexOf() will do the job: although it may have to be applied three times. There is also the matches() method if you want "regular expressions".
    Last edited by pbrockway2; 04-23-2012 at 02:47 AM.

  3. #3
    Tman is offline Member
    Join Date
    Apr 2012
    Posts
    4
    Rep Power
    0

    Default Re: Using Placeholders such as * and ? in a String

    Reading up on the indexOf method, how would you get it to find all three characters if it only finds the first?

    I also know at what index positions I expect the a's to be, so I was trying string.charAt(5) == "a" && string.charAt(7) =="a" etc, which I may try again actually, just realised I may of been doing it wrong.

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Using Placeholders such as * and ? in a String

    how would you get it to find all three characters if it only finds the first
    It returns the index of the first, then you use the other form of indexOf() that accepts a start index as well as a target string. If the a's are expected at known locations then that is what you should check for (it's a more restrictive condition).

    -----

    I'm sure you mean string.charAt(5)=='a' in your post ... and in your code.

  5. #5
    Tman is offline Member
    Join Date
    Apr 2012
    Posts
    4
    Rep Power
    0

    Default Re: Using Placeholders such as * and ? in a String

    ahh yes, thanks for that. :)

Similar Threads

  1. Replies: 3
    Last Post: 02-10-2012, 06:26 PM
  2. Replies: 12
    Last Post: 11-26-2010, 08:33 AM
  3. Replies: 1
    Last Post: 11-04-2010, 06:53 PM
  4. Replies: 7
    Last Post: 11-03-2009, 02:18 AM
  5. Replies: 5
    Last Post: 01-11-2009, 10:12 AM

Posting Permissions

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