Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

How String Comparison happens in Swift

in this example:

var str1 = "hello"
var str2 = "Hello"

if str1 < str2 { print("hello is less than Hello")}
else {print("hello is more than Hello")}

on what basis it is found that str1 is greater than str2?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Swift strings are compared according to the Unicode Collation Algorithm, which means that (effectively),

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 

and therefore "Hello" < "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

have the decomposed form

a: U+0061
?: U+0061, U+0308  // LATIN SMALL LETTER A + COMBINING DIAERESIS
b: U+0062

and therefore "a" < "?" < "b".

For more details and examples, see What does it mean that string and character comparisons in Swift are not locale-sensitive?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...