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 风格字符串的正确函数是什么?
基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
