字符串比较如何发生在斯威夫特
问题描述:
在这个例子:字符串比较如何发生在斯威夫特
var str1 = "hello"
var str2 = "Hello"
if str1 < str2 { print("hello is less than Hello")}
else {print("hello is more than Hello")}
凭什么发现str1和大于str2?
答
使用每个字符的Unicode值来比较两个字符串,逐个字符。由于h
具有比H
(U + 0048)更高的代码(U + 0068),str1
比str2
“大”。
基于这个问题下面马丁的评论,这比我说稍微复杂一些。有关更多详细信息,请参阅What does it mean that string and character comparisons in Swift are not locale-sensitive?。
答
夫特串根据 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?
相关:[?这是什么意思斯威夫特该字符串和字符比较没有语言环境敏感(http://stackoverflow.com/questions/25713975/what -does-IT-均是字符串和字符,比较功能于迅速 - 是 - 不是语言环境) –