减号和单引号在 if 语句中起什么作用?
在以下代码中,向比较的两个操作数添加相同的字母会更改结果。尽管-
不大于j
,但-k
大于jk
。
仅当操作数之一是减号 (-
) 或单引号 ('
) 时才会发生这种情况。
为什么会发生这种情况?规则是什么?
if - gtr j (echo - greater than j) else echo - less than j
if "-" gtr "j" (echo "-" greater than "j") else echo "-" less than "j"
echo.
if -k gtr jk (echo -k greater than jk) else echo -k less than jk
if "-k" gtr "jk" (echo "-k" greater than "jk") else echo "-k" less than "jk"
echo.
if ' gtr u (echo ' greater than u) else echo ' less than u
if "'" gtr "u" (echo "'" greater than "u") else echo "'" less than "u"
echo.
if 'v gtr uv (echo 'v greater than uv) else echo 'v less than uv
if "'v" gtr "uv" (echo "'v" greater than "uv") else echo "'v" less than "uv"
结果是:
- less than j
"-" less than "j"
-k greater than jk
"-k" greater than "jk"
' less than u
"'" less than "u"
'v greater than uv
"'v" greater than "uv"
In the following code, adding the same letter to both operands of the comparison changes the result. Despite -
being not greater than j
, -k
is greater than jk
.
This only happens if one of the operands is the minus sign (-
) or single quotation mark ('
).
Why does this happen? What are the rules?
if - gtr j (echo - greater than j) else echo - less than j
if "-" gtr "j" (echo "-" greater than "j") else echo "-" less than "j"
echo.
if -k gtr jk (echo -k greater than jk) else echo -k less than jk
if "-k" gtr "jk" (echo "-k" greater than "jk") else echo "-k" less than "jk"
echo.
if ' gtr u (echo ' greater than u) else echo ' less than u
if "'" gtr "u" (echo "'" greater than "u") else echo "'" less than "u"
echo.
if 'v gtr uv (echo 'v greater than uv) else echo 'v less than uv
if "'v" gtr "uv" (echo "'v" greater than "uv") else echo "'v" less than "uv"
The result is:
- less than j
"-" less than "j"
-k greater than jk
"-k" greater than "jk"
' less than u
"'" less than "u"
'v greater than uv
"'v" greater than "uv"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能假设字符串只是逐个字符进行比较,并获取它们的序数值。
那不是真的。整理比这复杂得多。
事实上,您可以在其他环境(例如 Windows PowerShell)中看到相同的情况:
字符串的顺序很可能也随您的区域设置而变化。
至于您在这里的特定问题,引用 Unicode 排序算法 (UTS #10) :
并解决您可能遇到的误解:
You may be assuming that strings are just compared character by character, taking their ordinal values.
That's not true. Collation is much more complex than that.
In fact, you can see the same in other environments, such as Windows PowerShell:
It could very well be that the order of strings varies with your locale as well.
As for your particular problem here, quoting from the Unicode Collation Algorithm (UTS #10):
and to solve the misconveption you're likely under: