Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare strings

I wanted to compare a string without actually defining one of them as a string, something like this,

if (string == "add") 

Do I have to declare "add" as a string or is it possible to compare in a similar way?

like image 378
Anon Avatar asked Jun 03 '11 03:06

Anon


People also ask

What is the best way to compare strings?

The right way of comparing String in Java is to either use equals(), equalsIgnoreCase(), or compareTo() method. You should use equals() method to check if two String contains exactly same characters in same order. It returns true if two String are equal or false if unequal.

Can you use == to compare strings?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

How do I compare strings with different strings?

Using String. equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.

What are the 3 ways to compare two string objects?

There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.


1 Answers

In C++ the std::string class implements the comparison operators, so you can perform the comparison using == just as you would expect:

if (string == "add") { ... } 

When used properly, operator overloading is an excellent C++ feature.

like image 58
e.James Avatar answered Oct 03 '22 08:10

e.James