简体   繁体   中英

How to make array case insensitive

I am writing a method that takes a string and searches through all the names for any that contain a matching substring, but how to I make the

targetSubstring 

which is the name the user has entered into a JTextField and the

namesArray[I].getname()

which is the data from the input file that has been stored in an array, not case-sensitive? So when the user types in for example Sam, I want it to be able to find Sammy and Isamer(since this contains sam inside the name). However, for this to happen I need Sam to not be case-sensitive. So how would I do this? I have tried the .toLowerCase because I thought that would work, but I get different compiler errors. So am I just to using the .toLowerCase right? Here is the last thing I've tried with the .toLowerCase, but it doesn't work.

   if (namesArray[i].getName().toLowerCase.contains(targetSubstring.toLowerCase))

Here is the method...

  private void match(String targetSubstring)
  {
    displayArea.setText("");
    displayArea.append("FIND RESULTS for: " + targetSubstring);
    displayArea.append("\n");
    displayArea.append("\n Name               Best Decade");
    displayArea.append("\n---------------     ---------------");
    for (int i = 0; i < namesArray.length; i++) {
      if (namesArray[i].getName().contains(targetSubstring))
      {
        displayArea.append("\n" + namesArray[i].getName() + "      " +
                        namesArray[i].bestDecade());
      }
     }
  }
targetSubstring = targetSubstring.toUpper ();
for (int i = 0; i < namesArray.length; i++) {
  String theName = namesArray[i].getName();
  if (theName.toUpper ().contains(targetSubstring))
  {
    displayArea.append("\n" + theName + "      " + namesArray[i].bestDecade());
  }
 }

Alternatively you can use code just like Gregory suggested but with the use of StringUtils from org.apache.commons.lang

for (int i = 0; i < namesArray.length; i++) {
  String theName = namesArray[i].getName();
  if (StringUtils.containsIgnoreCase(theName, targetSubstring ))
  {
    displayArea.append("\n" + theName + "      " + namesArray[i].bestDecade());
  }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM