Why use strcmp instead of = ? [MATLAB]

  • Context: MATLAB 
  • Thread starter Thread starter nickadams
  • Start date Start date
  • Tags Tags
    Matlab
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 10K views
nickadams
Messages
182
Reaction score
0
If a user answers "yes", "Yes", "y", or "Y" to an input question, I want to enter the while loop. But when I tried to use


user=input('blahblahblah [y/n]: ','s');

while user=='y' || user='Y' || user=='yes' || user=='Yes'


MATLAB recommends I change to strcmp. Why is this?
 
Physics news on Phys.org
To test if two strings are equivalent, use strcmp, which allows vectors of dissimilar length to be compared.

http://www.mathworks.com/help/techdoc/ref/relationaloperators.html

Even if the strings had the same length, using == might result in the creation of an intermediate logical array of the same size, whereas strcmp might stop comparing as soon as the first difference was encountered.
 
It's also a very good habit to learn if you ever move to C++ or Java, because in those languages == and strcmp() do fundamentally different things.

In C++, == checks if the two strings share the same memory, not if the contents of the memory are equal.

So for code like
String a = "string" + " one";
String b = "string one";
String c = a;

You get the strange result that a == c is true (because a and c are both references to the same String object), but a == b is false (because a and b are different String objects).

But strcmp(a,b) and strcmp(a,c) are both true, which is probably how you wanted the comparison to behave.
 
AlephZero said:
It's also a very good habit to learn if you ever move to C++ or Java, because in those languages == and strcmp() do fundamentally different things.

In C++, == checks if the two strings share the same memory, not if the contents of the memory are equal.

So for code like
String a = "string" + " one";
String b = "string one";
String c = a;

You get the strange result that a == c is true (because a and c are both references to the same String object), but a == b is false (because a and b are different String objects).

But strcmp(a,b) and strcmp(a,c) are both true, which is probably how you wanted the comparison to behave.

This is not correct. C++ has no String type. For, C++'s std::string type, http://msdn.microsoft.com/en-us/library/8ww0haah.aspx" does perform a lexicographical comparison, so a == b would be true. Also, you may not add two c-string literals in C++.


Java, which does have a String type, does not have an strcmp function at all. This functionality may be performed with the .equals method.
 
Last edited by a moderator: