Frank
Frank

Reputation: 2173

Find whether a string matches another string

I'd like to parse a string in order to see if it matches the entire string or a substring. I tried this:

String [] array = {"Example","hi","EXAMPLE","example","eXamPLe"};
String word;
...
if ( array[j].toUpperCase().contains(word) ||  array[j].toLowerCase().contains(word)  )
System.out.print(word + " ");

But my problem is:

When user enter the word "Example" (case sensitive) and in my array there is "Example" it doesn't print it, it only prints "EXAMPLE" and "example" that's because when my program compares the two strings it converts my array[j] string to uppercase or lowercase so it won't match words with both upper and lower cases like the word "Example".

So in this case if user enters "Examp" I want it to print:

Example EXAMPLE example eXamPLe

Upvotes: 0

Views: 167

Answers (6)

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51721

Submit this as your assignment. You'll definitely come off as unique.

String word = "Exam";
String [] array = {"Example","hi","EXAMPLE","example","eXamPLe"};

for (String str : array)
  if (str.matches("(?i)"+word+".*"))
    System.out.print(str + " "); // prints: Example EXAMPLE example eXamPLe

Upvotes: 0

argentum47
argentum47

Reputation: 2382

well, i think othehan using .equalsIgnoreCase u might also be interested in the Matcher( Java Regex). the links are self-explanaory: http://www.vogella.com/articles/JavaRegularExpressions/article.html http://docs.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html Pattern/Matcher group() to obtain substring in Java? String contains - ignore case

Upvotes: 0

zw324
zw324

Reputation: 27210

If you are just looking for full matches, use equalsIgnoreCase.

When partial match is needed you might need a trie or something similar.

Upvotes: 3

Sazzadur Rahaman
Sazzadur Rahaman

Reputation: 7126

You are looking for this:

if (array[j].toUpperCase().contains(word.toUpperCase())) {
    System.out.print(array[j]+ " ");
}

This will print:

Example EXAMPLE example eXamPLe

As you wanted!

Upvotes: 1

Tap
Tap

Reputation: 6522

Compare to the same case of word.

if ( array[j].toUpperCase().contains(word.toUpperCase()))
{
}

Upvotes: 1

Andy Thomas
Andy Thomas

Reputation: 86509

You can convert both the input string and the candidates to uppercase before calling contains().

if ( array[j].toUpperCase().contains( word.toUpperCase() ) ) {
    System.out.print(word + " ");
}

Upvotes: 5

Related Questions