简体   繁体   English

Java contains()方法无法正常工作

[英]Java contains() method not working properly

I'm writing small condition to check if certain character are exist or not in java. 我在写小写的条件来检查Java中是否存在某些字符。 This is my string: May i know how much I spent on food? 这是我的话:我可以知道我在食物上花了多少钱吗?

I'm checking if food string is exist or not, if i check "food" in if condition I'm getting proper response, if i use "Food" or "fOod" or "fOOd" or "fooD" its always going to else block. 我正在检查食物字符串是否存在,如果我在适当条件下检查“食物”,则得到正确的响应,如果我使用“食物”或“ fOod”或“ fOOd”或“ fooD”,它总是会否则阻止。 What I'm doing wrong here: 我在这里做错了什么:

String food = "may i know how much I spent on food"; 零食=“我可以知道我在食物上花了多少钱”;

if(food.contains("Food")) {
    System.out.println("Food Expense is 32");

} else {
    System.out.println("Not Matching");
}

That is because the difference in cases. 那是因为情况不同。 "Food".equals("food") will give you false. "Food".equals("food")会给你错误。 To solve the problem of cases you can convert everything to lower when searching 为了解决案例的问题,您可以在搜索时将所有内容转换为较低的

if (food.toLowerCase().contains("Food".toLowerCase())) {}

And you can have any variation of food in the if condition. 如果条件允许,您可以食用各种食物。 No need to worry about case sensitivity with this 无需为此担心大小写

Try this 尝试这个

if(food.toLowerCase().contains("Food".toLowerCase())) {
System.out.println("Food Expense is 32");

} else {
System.out.println("Not Matching");
}

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

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