简体   繁体   中英

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 any way in java that can do full text matching not partial? For example

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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