gpt4 book ai didi

swift - Swift 中的字符串比较是不可传递的

转载 作者:IT王子 更新时间:2023-10-29 05:37:54 24 4
gpt4 key购买 nike

我遇到了这个例子,其中 s1 < s2 和 s2 < s3 但 (s1 < s3) 是假的:

var str1 = "あいかぎ"
var str2 = "あいかくしつ"
var str3 = "あいがみ:"

print(str1 < str2) // True
print(str2 < str3) // True
print(str1 < str3) // False (?)

这是一个错误还是我们确实不能依赖字符串比较是可传递的(这破坏了我对字符串数组的排序)?我正在运行 Swift 3。

更新:所有这些都是假的

print(str1 < str3)       // False (?)
print(str1 == str3) // False (?)
print(str1 > str3) // False (?)

所以有些字符串不能相互比较?

更新:How does the Swift string more than operator work 中的评论指出 < 运算符的源代码在 https://github.com/apple/swift/blob/master/stdlib/public/core/String.swift 中,比较由 https://github.com/apple/swift/blob/master/stdlib/public/stubs/UnicodeNormalization.cpp 中的 _swift_stdlib_unicode_compare_utf8_utf8 处理。

更新:这些都是真的

print(str1 >= str3)  // True
print(str1 <= str3) // True

更新:String.localizedCompare() 也有问题。有两个字符串,其中 s1 = s2 但 s2 > s1:

str1 = "bảo toàn"
str2 = "bảo tồn"

print(str1.localizedCompare(str2) == .orderedSame) // true
print(str2.localizedCompare(str1) == .orderedDescending) // true

最佳答案

看起来这不应该发生:

Q: Is transitive consistency maintained by the [Unicode Collation Algorithm]?

A: Yes, for any strings A, B, and C, if A < B and B < C, then A < C. However, implementers must be careful to produce implementations that accurately reproduce the results of the Unicode Collation Algorithm as they optimize their own algorithms. It is easy to perform careless optimizations — especially with Incremental Comparison algorithms — that fail this test. Other items to check are the proper distinction between the bases of accents. For example, the sequence <u-macron, u-diaeresis-macron> should compare as less than <u-macron-diaeresis, u-macron>; this is a secondary distinction, based on the weighting of the accents, which must be correctly associated with the primary weights of their respective base letters.

(来源:Unicode Collation FAQ)

UnicodeNormalization.cpp文件中,调用了ucol_strcollucol_strcollIter,它们是the ICU project的一部分。 .这可能是 Swift 标准库或 ICU 项目中的错误。 I reported this issue to the Swift Bug Tracker .

关于swift - Swift 中的字符串比较是不可传递的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46230471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com