如何比较字符串

How to compare strings

本文关键字:字符串 比较 何比较      更新时间:2023-10-16

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

if (string == "add")

我必须将"add"声明为字符串吗?或者可以用类似的方式进行比较吗?

在C++中,std::string类实现了比较运算符,因此您可以像预期的那样使用==执行比较:

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

如果使用得当,运算符重载是一个优秀的C++特性。

您需要使用strcmp

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

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

我们在C++计算机语言中使用以下一组指令。

目标:验证std::string容器内的值是否等于"0";添加":

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