1

I have an ArrayList of strings and I want to perform a search method on them. So far I only have this:

public void searchNote(String searchCertainNote)
{
    for (String note: notes)
    {
        if (note.contains(searchCertainNote))
        {
            System.out.println(note);
        }
    }
}

I would like to improve this search method a bit by allowing the user to search for a string like:

String searchCertainString = "a?c" ... Possible search results: "abcd"; "a4c"; "Abc", "a22c", "a$c", etc...

The question mark "?" should represent all characters that are out there.

I did some googling and found out that I could implement this by using regex and String.matches() ...

But I still need your help on this!

Thanks =)

tschang
  • 11
  • 1
  • 3

2 Answers2

2

If the user will be entering a '?' as the wildcard (or joker as you called it), then, if you use Regex, you'll need to convert the '?' to '.' to use it in the Regex pattern. In Regex, the period matches any single character.

So, you'd need to change the user's input of "a?b" to "a.b".

If the '?' is meant to match at least one character, but possible more than one, then use '.+' instead. The '+' is a qualifier that means 'one or more of the preceding thing'.

So, you'd need to change the user's input of "a?b" to "a.+b". This pattern will match "axb" "axyb", but not "ab".

Here's a good beginner's guide for Java regular expression handling:

http://www.vogella.com/tutorials/JavaRegularExpressions/article.html

Darren
  • 184
  • 4
0

Do this:

if(searchCertainNote.length <= 0) {
    // String is empty, do something
    return;
}

for(int i = 0; i < searchCertainNote.length; i++) {
    if(searchCertainNote.charAt(i) == 'a') {
        if(searchCertainNote.length >= ((i + 1) + 1))) {
            if(searchCertainNote.charAt(i + 2) == 'c') {
                System.out.println(searchCertainNote.charAt(i) + searchCertainNote.charAt(i + 1) + searchCertainNote.charAt(i + 2));
                return;
            }
        } else {
            // Not found, so do something
            return;
        }
    }
}

You can trust completely on this code. It will print to screen a?c if found in ANY string that you enter and return, else it will do something you want and returns. It also detects empty and too short strings and avoids an ArrayIndexOutOfBoundsException. Good luck :D.

alesc3
  • 84
  • 11