How to compare strings

前端 未结 3 1310
悲哀的现实
悲哀的现实 2020-12-10 00:55

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 de

相关标签:
3条回答
  • 2020-12-10 01:23

    You could use strcmp():

    /* strcmp example */
    #include <stdio.h>
    #include <string.h>
    
    int main ()
    {
      char szKey[] = "apple";
      char szInput[80];
      do {
         printf ("Guess my favourite fruit? ");
         gets (szInput);
      } while (strcmp (szKey,szInput) != 0);
      puts ("Correct answer!");
      return 0;
    }
    
    0 讨论(0)
  • 2020-12-10 01:24

    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.

    0 讨论(0)
  • 2020-12-10 01:26

    You need to use strcmp.

    if (strcmp(string,"add") == 0){
        print("success!");
    }
    
    0 讨论(0)
提交回复
热议问题