简体   繁体   English

如何在C ++中比较base36值?

[英]How do I compare base36 values in C++?

As we all know, with C-style string comparisons, the value is dependent on the ASCII value of each character and just uses the strcmp function to compare. 众所周知,对于C风格的字符串比较,该值取决于每个字符的ASCII值,并且仅使用strcmp函数进行比较。 I'm confused that what the std::string compare depends on? 我对std::string比较依赖于什么感到困惑?

Although I have searched Google, I still didn't find the answer. 尽管我已经搜索过Google,但仍然没有找到答案。

In addition, if strings are all base36 strings and they are all in lower case, could I compare their values by strings directly? 此外,如果所有字符串都是base36字符串,并且全部都是小写字母,我可以直接按字符串比较它们的值吗? Or I should convert them as a long variable using the strtol function? 还是应该使用strtol函数将它们转换为长变量? Which method is better? 哪种方法更好?

Your outset "As we all know, with C-style string comparisons, the value is dependent on the ASCII value of each character..." is unfortunately wrong already. 不幸的是,您的开头“众所周知,对于C风格的字符串比较,该值取决于每个字符的ASCII值...”。 With eg UTF-8 strings and various forms of collation, that's simply untrue. 使用UTF-8字符串和各种形式的排序规则,这简直是不正确的。

Then "...and just uses the strcmp function to compare." 然后“ ...并且仅使用strcmp函数进行比较”。 is also wrong, because C-style strings don't have an inherent way to compare but multiple ways that also depend on eg the encoding and locale. 这也是错误的,因为C风格的字符串没有固有的比较方式,而是多种方式,这些方式也取决于例如编码和语言环境。 You could use strcmp() for bytewise equality comparisons though, but that won't always give you expected results. 您可以使用strcmp()进行按字节相等性比较,但这并不总能给您预期的结果。

To answer your question what std::string uses, that's simple. 要回答您的问题std::string使用什么,很简单。 std::string is a specialization of the std::basic_string template and it delegates comparisons to its char_traits template parameter. std::stringstd::basic_string模板的专门化版本,它将比较委托给其char_traits模板参数。 This parameter typically uses memcmp() . 此参数通常使用memcmp() It can not possibly use strcmp() , because other than a C-style string, std::string can include null chars, but strcmp() would stop at those. 它不可能使用strcmp() ,因为除C风格的字符串外, std::string可以包含null字符,但strcmp()会在这些字符处停止。

std::string compare depends upon 'ASCII values' in exactly the same way that strcmp does. std :: string compare依赖于“ ASCII值”,与strcmp完全相同。

For base36 comparisons, simple string comparison (either strcmp or std::string) doesn't work because "00123" and "123" are equal when representing base36 integers but they compare differently as strings. 对于base36比较,简单的字符串比较(strcmp或std :: string)不起作用,因为在表示base36整数时“ 00123”和“ 123”相等,但它们作为字符串进行比较的方式有所不同。 Neither does strtol work very well because of integer overflow. 由于整数溢出,strtol都不能很好地工作。 Instead you should probably write your own comparison routine that removes leading zeros, then compares length and finally for strings of equal length does a string comparison. 相反,您可能应该编写自己的比较例程,该例程删除前导零,然后比较长度,最后对相等长度的字符串进行字符串比较。

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

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