在java中使字符串不区分大小写
我的应用程序中有一个问题我有一个在java中使字符串不区分大小写,java,string,search,case-sensitive,case-insensitive,Java,String,Search,Case Sensitive,Case Insensitive,我的应用程序中有一个问题我有一个字符串,其中包含一个用于搜索的单词,然后我使用这个单词从长文本中搜索,我希望包含搜索单词的所有单词都返回(例如,word=word=word)。谢谢 String tstr1是文本,String String是搜索的键,现在我想计算搜索的键在文本中的次数(不区分大小写)。谢谢java.lang.String有一个方法boolean equalsIgnoreCase(String-anotherString),您应该在这里使用它 在调用.equals()之前,最好将
字符串
,其中包含一个用于搜索的单词,然后我使用这个单词从长文本中搜索,我希望包含搜索单词的所有单词都返回(例如,word=word=word)。谢谢
String tstr1
是文本,String String
是搜索的键,现在我想计算搜索的键在文本中的次数(不区分大小写)。谢谢java.lang.String
有一个方法boolean equalsIgnoreCase(String-anotherString)
,您应该在这里使用它
在调用
.equals()
之前,最好将字符串转换为小写或大写。这样做需要对两个字符串进行整体操作,而equalsIgnoreCase
可以在第一次不匹配时退出。您要查找的是String
类的equalsIgnoreCase
公共布尔equalsIgnoreCase(字符串另一个字符串)
将此字符串与另一个字符串进行比较,忽略大小写注意事项。如果两个字符串长度相同,且两个字符串中的对应字符大小写相同,则视为相等忽略大小写
您也可以使用toLowerCase()
或toUpperCase()
但我认为使用equalsIgnoreCase()
更具可读性
这也更有效,正如我们所指出的那样。这是因为一旦出现不匹配,equalsIgnoreCase()
将停止比较字符串
更多关于这个。也请阅读。在这个场景中,我们使用了
模式
类来实现所有情况下的大小写不敏感。
例如:
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
}
}
为了计算段落中不区分大小写的单词,我们还使用了
模式类和while
循环:
例如:
试试这个:
if (string1.equalsIgnoreCase(string2)){
Do.somthing
}else{etc.}
注意:方法equals()
继承自对象
,因此不应更改其签名 你能发布你尝试过的代码吗?你是在寻找equalsIgnoreCase()还是toLower()/toUpper()。如果不是,请进一步说明你的问题是的,我支持loking equalsIgnoreCase()或toLower()/toUpper(),例如,如果我的搜索词是word
,而文本中的词是words
,我想找到它……而且效率更高。@Bathsheba也是这样。我会在答案中加上这个。非常感谢。谢谢你的回答,我更新了我的问题,你能告诉我如何实现这一点吗。计算searchKey
在searchOn
中的次数。非常感谢。
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);
}
}
if (string1.equalsIgnoreCase(string2)){
Do.somthing
}else{etc.}