C++ 如何比较字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6222583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 19:42:35  来源:igfitidea点击:

How to compare strings

c++stringcompare

提问by Anon

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?

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

回答by e.James

In C++ the std::string class implements the comparison operators, so you can perform the comparison using ==just as you would expect:

在 C++ 中, std::string 类实现了比较运算符,因此您可以按照==预期使用以下方法执行比较:

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

When used properly, operator overloadingis an excellent C++ feature.

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

回答by Christopher Armstrong

You need to use strcmp.

您需要使用strcmp.

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

回答by Algorithmist

You could use strcmp():

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