为什么“echo strcmp('60', '100');”在php输出5中?
PHP 关于这个函数的文档有点稀疏,我读到这个函数比较 ASCII 值,所以......
echo strcmp('hello', 'hello');
//outputs 0 as expected - strings are equal.
echo '<hr />';
echo strcmp('Hello', 'hello');
//outputs -32, a negative number is expected as
//uppercase H has a lower ASCII value than lowercase h.
echo '<hr />';
echo strcmp('60', '100');
//outputs 5.
最后一个例子让我感到困惑。我不明白为什么它输出正数。
- ASCII 值 0 = 48
- ASCII 值 1 = 49
ASCII 值 6 = 54
“60”的总 ASCII 值 = (54 + 48) = 102< /p>
- '100' 的总 ASCII 值 = (49 + 48 + 48) = 145
strcmp() 函数表示“60”“大于”“100”,尽管“100”的 ASCII 值和字符串长度似乎大于'60'
谁能解释一下原因吗?
谢谢
PHP's documentation on this function is a bit sparse and I have read that this function compares ASCII values so...
echo strcmp('hello', 'hello');
//outputs 0 as expected - strings are equal.
echo '<hr />';
echo strcmp('Hello', 'hello');
//outputs -32, a negative number is expected as
//uppercase H has a lower ASCII value than lowercase h.
echo '<hr />';
echo strcmp('60', '100');
//outputs 5.
The last example is confusing me. I don't understand why it is outputting a positive number.
- ASCII Value of 0 = 48
- ASCII Value of 1 = 49
ASCII Value of 6 = 54
Total ASCII value of '60' = (54 + 48) = 102
- Total ASCII value of '100' = (49 + 48 + 48) = 145
The strcmp() functions is saying that '60' is "greater" than '100' even though it seems that the ASCII value and string length of '100' is greater than '60'
Can anyone explain why?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
strcmp()
返回字符串之间第一个不匹配字符的差异。6
-1
是 5。当您查看它时,您可能看不到字符或数字 - 只是数字
strcmp()
returns the difference of the first non-matching character between the strings.6
-1
is 5.When you look at it, you are probably not seeing the characters or digits—just the numbers
因为
strcmp()
在找到的第一个差异处停止。因此,ASCII 值“1”和 ASCII 值“6”之间存在差异Because
strcmp()
stops at the first difference it finds. Hence the difference between the ASCII value of '1' and the ASCII value of '6'6 比 1 “大”5。这是词法比较。第一个字符不同,这就是比较停止的地方。
6 is 5 "larger" than 1. This is lexical comparison. The first character is different, that's where the comparison stops.