我想将字符串与字符串文字进行比较;像这样的:
if (string == "add")
我是否必须将
"add"
声明为字符串,或者是否可以以类似的方式进行比较?
您需要使用
strcmp
。
if (strcmp(string,"add") == 0){
print("success!");
}
std::string
std::string
有一个运算符重载,允许您将其与另一个字符串进行比较。
std::string string = "add";
if (string == "add") // true
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)
strcmp
(与 C 兼容)如果这些选项都不可用,或者您需要编写同时适用于 C 和 C++ 的代码:
#include <string.h>
// ...
const char* string = "add";
if (strcmp(string, "add") == 0) // true
你可以使用
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
容器内的值是否等于“add”:
if (sString.compare(“add”) == 0) { //if equal
// Execute
}