How to compare strings

[亡魂溺海] 提交于 2019-12-28 14:01:51

问题


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?


回答1:


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.




回答2:


You need to use strcmp.

if (strcmp(string,"add") == 0){
    print("success!");
}



回答3:


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;
}


来源:https://stackoverflow.com/questions/6222583/how-to-compare-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!