如何检查字符串是否等于字符串文字

问题描述 投票:0回答:5

我想将字符串与字符串文字进行比较;像这样的:

if (string == "add")

我是否必须将

"add"
声明为字符串,或者是否可以以类似的方式进行比较?

c++ string compare string-literals
5个回答
66
投票

在 C++ 中,

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

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

如果使用得当,运算符重载是一项出色的 C++ 功能。


7
投票

您需要使用

strcmp

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

0
投票

选项 A - 使用
std::string

std::string
有一个运算符重载,允许您将其与另一个字符串进行比较。

std::string string = "add";
if (string == "add") // true

选项 B - 使用
std::string_view
(C++17)

如果其中一个操作数还不是

std::string
std::string_view
,您可以将任一操作数包装在
std::string_view
中。这是非常便宜的,并且不需要任何动态内存分配。

#include <string_view>
// ...

if (std::string_view(string) == "add")
// or
if (string == std::string_view("add"))
// or
using namespace std::string_literals;
if (string == "add"sv)

选项 C - 使用
strcmp
(与 C 兼容)

如果这些选项都不可用,或者您需要编写同时适用于 C 和 C++ 的代码:

#include <string.h>
// ...

const char* string = "add";
if (strcmp(string, "add") == 0) // true

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

-1
投票

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

目的:验证

std::string
容器内的值是否等于“add”:

if (sString.compare(“add”) == 0) { //if equal
    // Execute
}
© www.soinside.com 2019 - 2024. All rights reserved.