Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace emoji characters with their descriptions in a Swift string

I'm looking for a way to replace emoji characters with their description in a Swift string.

Example:

Input "This is my string 😄"

I'd like to replace the 😄 to get:

Output "This is my string {SMILING FACE WITH OPEN MOUTH AND SMILING EYES}"

To date I'm using this code modified from the original code of this answer by MartinR, but it works only if I deal with a single character.

let myCharacter : Character = "😄"
let cfstr = NSMutableString(string: String(myCharacter)) as CFMutableString
var range = CFRangeMake(0, CFStringGetLength(cfstr))
CFStringTransform(cfstr, &range, kCFStringTransformToUnicodeName, Bool(0))
var newStr = "\(cfstr)"

// removing "\N"  from the result: \N{SMILING FACE WITH OPEN MOUTH AND SMILING EYES}
newStr = newStr.stringByReplacingOccurrencesOfString("\\N", withString:"")

print("\(newStr)") // {SMILING FACE WITH OPEN MOUTH AND SMILING EYES}

How can I achieve this?

like image 659
Cue Avatar asked Feb 07 '23 19:02

Cue


1 Answers

Simply do not use a Character in the first place but use a String as input:

let cfstr = NSMutableString(string: "This 😄 is my string 😄") as CFMutableString

that will finally output

This {SMILING FACE WITH OPEN MOUTH AND SMILING EYES} is my string {SMILING FACE WITH OPEN MOUTH AND SMILING EYES}

Put together:

func transformUnicode(input : String) -> String {
    let cfstr = NSMutableString(string: input) as CFMutableString
    var range = CFRangeMake(0, CFStringGetLength(cfstr))
    CFStringTransform(cfstr, &range, kCFStringTransformToUnicodeName, Bool(0))
    let newStr = "\(cfstr)"
    return newStr.stringByReplacingOccurrencesOfString("\\N", withString:"")
}

transformUnicode("This 😄 is my string 😄")
like image 101
luk2302 Avatar answered Feb 09 '23 12:02

luk2302