Swift 中的字符串比较是如何发生的 [英] How String Comparison happens in Swift
本文介绍了Swift 中的字符串比较是如何发生的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在这个例子中:
var str1 = "hello"
var str2 = "Hello"
if str1 < str2 { print("hello is less than Hello")}
else {print("hello is more than Hello")}
根据什么发现str1大于str2?
on what basis it is found that str1 is greater than str2?
推荐答案
Swift 字符串根据Unicode 整理算法,这意味着(有效地)
Swift strings are compared according to the Unicode Collation Algorithm, which means that (effectively),
- 每个字符串都放入"Unicode 规范化表格 D",
- 按字典顺序比较这些分解"字符串的 Unicode 标量值.
在您的示例中,"hello
" 和 "Hello"
具有 Unicode 值
In your example, "hello
" and "Hello"
have the Unicode values
hello: U+0068, U+0065, U+006C, U+006C, U+006F
Hello: U+0048, U+0065, U+006C, U+006C, U+006F
因此 "Hello" <你好"
.
规范化"或分解"是相关的,例如对于字符带有变音符号.例如,
The "normalization" or "decomposing" is relevant e.g. for characters with diacritical marks. As an example,
a = U+0061
ä = U+00E4
b = U+0062
有分解形式
a: U+0061
ä: U+0061, U+0308 // LATIN SMALL LETTER A + COMBINING DIAERESIS
b: U+0062
因此 "a" <啊"<"b"
.
有关更多详细信息和示例,请参阅 Swift 中的字符串和字符比较不区分区域设置是什么意思?
For more details and examples, see What does it mean that string and character comparisons in Swift are not locale-sensitive?
这篇关于Swift 中的字符串比较是如何发生的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文