【问题标题】:How String Comparison happens in SwiftSwift 中的字符串比较是如何发生的
【发布时间】:2019-05-17 17:56:10
【问题描述】:

在这个例子中:

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 string


【解决方案1】:

Swift 字符串是根据 Unicode Collation Algorithm, 这意味着(有效地),

在您的示例中,"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" &lt; "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" &lt; "ä" &lt; "b"

更多详情和示例,请参阅What does it mean that string and character comparisons in Swift are not locale-sensitive?

【讨论】:

    【解决方案2】:

    使用每个字符的 Unicode 值逐个字符地比较两个字符串。由于h 的代码(U+0068)高于H(U+0048),str1str2“更大”。

    根据 Martin 在问题下方的评论,它比我所说的要复杂一些。详情请见What does it mean that string and character comparisons in Swift are not locale-sensitive?

    【讨论】:

      【解决方案3】:

      我认为它是基于字典顺序的。https://en.wikipedia.org/wiki/Lexicographical_order

      【讨论】:

        【解决方案4】:

        在 Swift 4.2 中 - //Unicode 值让你知道为什么“hello”大于“Hello”,因为两个字符串的长度相同。

        var str1 = "hello"
        var str2 = "Hello"
        
        if (str1 < str2){
            print("hello is less than Hello")
        }
        else {
            print("hello is more than Hello")
        }
        
        print(str1.unicodeScalars[str1.unicodeScalars.startIndex].value)
        print(str2.unicodeScalars[str2.unicodeScalars.startIndex].value)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-03-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-01-31
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多