What is the proper function for comparing two C-style strings?(比较两个 C 风格字符串的正确函数是什么?)
问题描述
所以我进退两难了.我需要比较两个 C 风格的字符串,然后搜索最合适的函数:
So I have a dilemma. I need to compare two C-style strings and I searched for the functions that would be the most appropiate:
memcmp //Compare two blocks of memory (function)
strcmp //Compare two strings (function )
strcoll //Compare two strings using locale (function)
strncmp //Compare characters of two strings (function)
strxfrm //Transform string using locale (function)
我认为第一个是地址,所以这个想法已经出来了.第二个听起来对我来说是最好的选择,但我还是想听听反馈.其他三个让我一无所知.
The first one I think is for addresses, so the idea is out. The second one sounds like the best choice to me, but I wanna hear feedback anyway. The other three leave me clueless.
推荐答案
对于一般的字符串比较,strcmp 是合适的函数.您应该使用 strncmp 仅比较字符串中的一些字符(例如,前缀),并使用 memcmp 比较内存块.
For general string comparisons, strcmp is the appropriate function. You should use strncmp to only compare some number of characters from a string (for example, a prefix), and memcmp to compare blocks of memory.
也就是说,由于您使用的是 C++,因此您应该完全避免这种情况并使用 std::string 类,它比 C 风格的字符串更易于使用且通常更安全.您只需使用 == 运算符即可轻松比较两个 std::string 的相等性.
That said, since you're using C++, you should avoid this altogether and use the std::string class, which is much easier to use and generally safer than C-style strings. You can compare two std::strings for equality easily by just using the == operator.
希望这会有所帮助!
这篇关于比较两个 C 风格字符串的正确函数是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:比较两个 C 风格字符串的正确函数是什么?
基础教程推荐
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
