0

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
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Frank
  • 2,083
  • 8
  • 34
  • 52

6 Answers6

5

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 + " ");
}
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
3

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

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

zw324
  • 26,764
  • 16
  • 85
  • 118
1

Compare to the same case of word.

if ( array[j].toUpperCase().contains(word.toUpperCase()))
{
}
Tap
  • 6,332
  • 3
  • 22
  • 25
1

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!

Sazzadur Rahaman
  • 6,938
  • 1
  • 30
  • 52
0

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

Community
  • 1
  • 1
argentum47
  • 2,385
  • 1
  • 18
  • 20
0

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
Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89