在此示例中:
var str1 = "hello"
var str2 = "Hello"
if str1 < str2 { print("hello is less than Hello")}
else {print("hello is more than Hello")}
根据什么发现str1大于str2?
最佳答案
Swift 字符串根据 Unicode Collation Algorithm , 这意味着(有效地),
- 每个字符串都放入 "Unicode Normalization Form D" ,
- 按字典顺序比较这些“分解”字符串的 unicode 标量值。
在您的示例中,"hello
"和 "Hello"
具有 Unicode 值
hello: U+0068, U+0065, U+006C, U+006C, U+006F
Hello: U+0048, U+0065, U+006C, U+006C, U+006F
因此 "Hello" < "hello"
.
“标准化”或“分解”是相关的,例如对于角色 带有变音符号。举个例子,
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"
.
有关更多详细信息和示例,请参阅 What does it mean that string and character comparisons in Swift are not locale-sensitive?
关于swift - Swift 中字符串比较是如何发生的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55383827/