简体   繁体   English

使字符串在Java中不区分大小写

[英]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). 我的应用程序中有一个问题,我有一个包含要搜索的单词的String ,然后使用该单词从长文本中搜索,我希望包含搜索到的单词的所有单词都返回(例如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). String tstr1是文本,而String string是搜索到的键,现在我要计算搜索到的键在文本中的次数(不区分大小写)。 Thanks 谢谢

What you are looking for is equalsIgnoreCase of the String class 你所寻找的是equalsIgnoreCase的的String

public boolean equalsIgnoreCase(String anotherString) 公共布尔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. 您还可以使用toLowerCase()toUpperCase()但我认为使用equalsIgnoreCase()更具有可读性。

This is also more efficient as was pointed by Bathsheba . 正如Bathsheba所指出的,这也更加有效。 This is because equalsIgnoreCase() will stop comparing the string as soon as a mismatch occurs. 这是因为,一旦发生不匹配, equalsIgnoreCase()将停止比较字符串。

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. java.lang.String有一个方法boolean equalsIgnoreCase(String anotherString) ,这是您应该在此处使用的方法。

It's preferred to converting the strings to lower or upper case prior to calling .equals() . 最好在调用.equals()之前将字符串转换为小写或大写。 Do in that requires you to operate on both strings in their entirety whereas equalsIgnoreCase can exit on the first mismatch. 要做到这一点,您需要完整地处理两个字符串,而equalsIgnoreCase可以在第一个不匹配时退出。

In this scenario we used Pattern class to achieve case insensitive in all case. 在这种情况下,我们使用Pattern类在所有情况下都实现不区分大小写。 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: 为了对不区分大小写的段落中的单词进行计数,我们还使用了带有while循环的Pattern类:

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. 注意: equals()方法是从Object继承的,因此不应更改其签名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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