开发者

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 :)

I am trying to match 2 strings if they match it should return 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 a开发者_如何转开发ny way in java that can do full text matching not partial? For example

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

thanks ! ! !


Why not just use the built-in String equals() method?

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.


use equals or equalsIgnoreCase on java.util.String for matching strings. You also need to check for null on the object you are comparing, I would generally prefer using commons StringUtils for these purposes. 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. Thus, this prints false and true.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜