简体   繁体   English

java字符串匹配问题

[英]java string matching problem

I am facing a very basic problem. 我面临一个非常基本的问题。 Some time small things can take your whole day :( but thank to stackoverflow memebers who always try to help :) 有些时候小事情可能需要你一整天:(但感谢stackoverflow memebers总是试图帮助:)

I am trying to match 2 strings if they match it should return TRUE 我试图匹配2个字符串,如果匹配它应该返回TRUE

now I am using this 现在我正在使用它

if (var1.indexOf(var2) >= 0) {
return true;
}

But if var1 has value "maintain" and var2 has value "inta" or "ain" etc. it still return true :(. Is there any way in java that can do full text matching not partial? For example 但是如果var1的值为“maintain”且var2的值为“inta”或“ain”等,它仍会返回true :(。在java中是否有任何方法可以进行全文匹配而不是部分?例如

if("mango"=="mango"){
return true;
}

thanks ! 谢谢 ! ! !

为什么不使用内置的String equals()方法?

return var1.equals(var2);
if( "mango".equals("mango") ) { 
   return true;
}

Be careful not to use == for string comparisons in Java unless you really know what you're doing. 除非你真的知道自己在做什么,否则小心不要在Java中使用==进行字符串比较。

use equals or equalsIgnoreCase on java.util.String for matching strings. java.util.String上使用equalsequalsIgnoreCase来匹配字符串。 You also need to check for null on the object you are comparing, I would generally prefer using commons StringUtils for these purposes. 您还需要检查要比较的对象的null ,我通常更喜欢使用commons StringUtils来实现这些目的。 It has very good utils for common string operations. 它具有很好的常用字符串操作功能。

Here's an example to show why == is not what you want: 这是一个示例,说明为什么==不是你想要的:

String s1 = new String("something");
String s2 = new String("something");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));

In effect, while s1 and s2 contains the same sequence of characters, they are not referring to the same location in memory. 实际上,虽然s1s2包含相同的字符序列,但它们并不是指内存中的相同位置。 Thus, this prints false and true . 因此,这打印falsetrue

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

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