简体   繁体   中英

Make the string case insensitive in java

I have a question in my app I have a String which contain a word for search, then I use this word to search from a long Text, I want that all words that contain the searched word to return (eg WoRd = word = WORD). Thanks.

private static int countWords(String tstr1, String string)
    {   
        int i = 0;
        Scanner s = new Scanner(tstr1);

        while (s.hasNext()) 
        {
            if (s.next().equals(string)) 
                i++;

        }

        return i;
    }
}

String tstr1 is the text and String string is the searched key, now I want to count how many times the searched key is in text (to be case insensitive). Thanks

What you are looking for is equalsIgnoreCase of the String class

public boolean equalsIgnoreCase(String anotherString)

Compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length and corresponding characters in the two strings are equal ignoring case.

You can also use toLowerCase() or toUpperCase() but I think using equalsIgnoreCase() is more readable.

This is also more efficient as was pointed by Bathsheba . This is because equalsIgnoreCase() will stop comparing the string as soon as a mismatch occurs.

More on this here . Read this too.

java.lang.String has a method boolean equalsIgnoreCase(String anotherString) which is what you should be using here.

It's preferred to converting the strings to lower or upper case prior to calling .equals() . Do in that requires you to operate on both strings in their entirety whereas equalsIgnoreCase can exit on the first mismatch.

In this scenario we used Pattern class to achieve case insensitive in all case. For example:

import java.util.regex.Pattern;

/**
*
* @author developerbhuwan
*/
public class HowToUseCaseInsensitive {

   public static void main(String[] args) {
       String searchKey = "cAt";
       String searchOn = "Cat is an animal";

      // In searchOn String is present but when
      // we use contains method of string then not found
      // due to case sensitive comparision
      if (searchOn.contains(searchKey)) {
          System.out.println("Cat found in searchIn String");
      } else {
          System.out.println("Cat not found in searchIn String");
      }

     // Output => Cat not found in searchIn String
     // To achieve case insensitive comparison
     // perfect solution for all case is by using
     // Pattern class as below
     if (Pattern.compile(Pattern.quote(searchKey),
        Pattern.CASE_INSENSITIVE).matcher(searchOn).find()) {
          System.out.println("Cat found in searchIn String");
    } else {
          System.out.println("Cat not found in searchIn String");
    }
   // Now Output => Cat found in searchIn String
  }
}

To count words in paragraph with case insensitive we also used Pattern class with while loop:

For example:

public class CountWordsInParagraphCaseInsensitive {


    public static void main(String[] args) {
        StringBuilder paragraph = new StringBuilder();
        paragraph.append("I am at office right now.")
                .append("I love to work at oFFicE.")
                .append("My OFFICE located at center of kathmandu valley");
        String searchWord = "office";
        Pattern pattern = Pattern.compile(searchWord, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(paragraph);
        int count = 0;
        while (matcher.find())
            count++;
        System.out.println(count);

    }

}

Try this:

if (string1.equalsIgnoreCase(string2)){
    Do.somthing 
}else{etc.}

Note: The method equals() is inherited from Object , so its signature should not be changed.

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