Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Why use strcmp instead of = ? [MATLAB]

  1. Oct 6, 2011 #1
    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?
     
  2. jcsd
  3. Oct 6, 2011 #2
    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.
     
  4. Oct 9, 2011 #3

    AlephZero

    User Avatar
    Science Advisor
    Homework Helper

    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.
     
  5. Oct 9, 2011 #4
    This is not correct. C++ has no String type. For, C++'s std::string type, http://msdn.microsoft.com/en-us/library/8ww0haah.aspx" [Broken] 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: May 5, 2017
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Why use strcmp instead of = ? [MATLAB]
  1. 3D plot using Matlab (Replies: 1)

  2. SHO using MATLAB (Replies: 7)

Loading...