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
256 views
in Technique[技术] by (71.8m points)

ios - How to separate emojis entered (through default keyboard) on textfield

I entered a two emojis in textfield ?????????????, here I'm getting total number of 5 characters length whereas 4 characters for first emoji and 1 character for second. Looks like apple has combined 4 emojis to form a one.

I'm looking for the swift code where I can separate each of emojis separately, suppose by taking the above example I should be getting 2 strings/character separately for each emoji.

Can any one help me to solve this, I've tried many things like regex separation or componentsSeparatedByString or characterSet. but unfortunately ended up with negative.

Thanks in advance.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Update for Swift 4 (Xcode 9)

As of Swift 4 (tested with Xcode 9 beta) a "Emoji ZWJ Sequence" is treated as a single Character as mandated by the Unicode 9 standard:

let str = "?????????????"
print(str.count) // 2
print(Array(str)) //  ["???????????", "??"]

Also String is a collection of its characters (again), so we can call str.count to get the length, and Array(str) to get all characters as an array.


(Old answer for Swift 3 and earlier)

This is only a partial answer which may help in this particular case.

"???????????" is indeed a combination of four separate characters:

let str = "?????????????" //
print(Array(str.characters))

// Output: ["???", "???", "???", "??", "??"]

which are glued together with U+200D (ZERO WIDTH JOINER):

for c in str.unicodeScalars {
    print(String(c.value, radix: 16))
}

/* Output:
1f468
200d
1f468
200d
1f467
200d
1f467
1f60d
*/

Enumerating the string with the .ByComposedCharacterSequences options combines these characters correctly:

var chars : [String] = []
str.enumerateSubstringsInRange(str.characters.indices, options: .ByComposedCharacterSequences) {
    (substring, _, _, _) -> () in
    chars.append(substring!)
}
print(chars)

// Output: ["???????????", "??"]

But there are other cases where this does not work, e.g. the "flags" which are a sequence of "Regional Indicator characters" (compare Swift countElements() return incorrect value when count flag emoji). With

let str = "????"

the result of the above loop is

["??", "??"]

which is not the desired result.

The full rules are defined in "3 Grapheme Cluster Boundaries" in the "Standard Annex #29 UNICODE TEXT SEGMENTATION" in the Unicode standard.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...