如何比较字符串

时间:2011-06-03 03:10:38

标签: c++ string compare

我想比较一个字符串而不将其中一个实际定义为字符串,类似这样,

if (string == 'add')

我是否必须将'add'声明为字符串,还是可以以类似的方式进行比较?

4 个答案:

答案 0 :(得分:61)

在C ++中,std :: string类实现comparison operators,因此您可以使用==执行比较,就像您期望的那样:

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

如果使用得当,operator overloading是一个出色的C ++功能。

答案 1 :(得分:9)

您需要使用strcmp

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

答案 2 :(得分:1)

您可以使用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;
}

答案 3 :(得分:0)

我们在 C++ 计算机语言中使用以下指令集。
目标:验证 std::string 容器内的值是否等于“add”

if (sString.compare(“add”) == 0) { //if equal
    //execute
}

谢谢。

相关问题