简体   繁体   English

C ++字符串比较

[英]c++ string comparison

If I have two pieces of character data, what is the best way to compare them (test for equality with ==)? 如果我有两个字符数据,比较它们的最佳方法是什么(用==测试相等性)? That is, which type is best for this comparison? 也就是说,哪种类型最适合此比较? A const char*, a string? const char *,字符串?

Thanks very much 非常感谢

If your goal is simply to compare strings for equality then it doesn't really matter whether you use null-terminated strings or some string container like std::string . 如果您的目标只是比较字符串是否相等,那么使用空终止的字符串还是使用诸如std::string类的字符串容器并不重要。

You can use std::strcmp to compare two null-terminated strings just as easily as you can use operator== to compare two std::string objects. 您可以使用std::strcmp比较两个以null终止的字符串,就像使用operator==比较两个std::string对象一样容易。 The overloaded operator does make code cleaner and easier to read in most cases. 在大多数情况下,重载的运算符的确使代码更干净,更易于阅读。

Of course, since you're programming in C++, you should be using std::string or some other string container and not manipulating raw null-terminated data, wherever possible. 当然,由于您使用C ++进行编程,因此应尽可能使用std::string或其他字符串容器,并且不要操纵原始的以null终止的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM