【问题标题】:Why can I use char but not string with stricmp()?为什么我可以在 stricmp() 中使用 char 但不能使用字符串?
【发布时间】:2017-09-11 15:05:28
【问题描述】:

这是代码:

char s[101], s1[101];
cin >> s >> s1;
cout << stricmp(s, s1);

我尝试将ss1 声明为std::string,但没有成功。有人可以解释一下为什么stricmp() 可以与char[] 一起使用,但不能与std::string 一起使用吗?

【问题讨论】:

  • 当您说“它不起作用”时,您可能应该更具体一点。你期待什么结果,你得到什么结果?
  • 只是因为我觉得你不知道它并且它是相关的 - 你知道char* 是什么吗?
  • 您可以将ss1 声明为std::string,但不要调用stricmp(s, s1);,而是像stricmp(s.c_str(), s1.c_str()); 那样调用它
  • 为什么只能使用 chars ?为什么我不能将它们作为字符串输入。 这表明您还不了解该语言的基础知识。请从a good book 学习该语言的基础知识。
  • C++ 中不区分大小写的字符串比较,另见stackoverflow.com/questions/11635/…

标签: c++


【解决方案1】:

在比较之前,您可能需要考虑将字符串全部转换为大写或全部小写:

std::string s1;
std::string s2;
std::cin >> s1 >> s2;
std::transform(s1.begin(), s1.end(),
               s1.begin(),
               std::tolower);
std::transform(s2.begin(), s2.end(),
               s2.begin(),
               std::tolower);
if (s1 == s2)
{
  std::cout << "s1 and s2 are case insensitive equal.\n";
}
else
{
  std::cout << "s1 and s2 are different.\n";
}

【讨论】:

    【解决方案2】:

    这是因为 stricmp() 不接受 std::string 值作为参数。

    请改用std::basic_string::compare()

    std::string s ("s");
    std::string s1 ("s1");
    
    if (s.compare(s1) != 0) // or just if (s != s1)
      std::cout << s << " is not " << s1 << std::endl;
    

    如果您需要不区分大小写的比较,则需要创建自己的函数,可能使用std::tolower() 就像this example 一样,或者只使用boost::iequals() 就像this other example 一样。

    【讨论】:

    • compare 不是不区分大小写的比较,而 stricmp 是。
    • 另外,在您的示例中,compare 甚至不需要。你可以写if (s != s1)
    • @NathanOliver,感谢您的建议,已添加到示例中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 2017-01-31
    • 2011-10-11
    • 2016-12-30
    • 1970-01-01
    相关资源
    最近更新 更多