Full string power with CFStringTransform

Powerful languages have great string manipulation capabilities, today we’ll have a look at what Objective-C offers.

CFStringTransform is part of the Core Foundation framework, it will let you manipulate strings of both NSString and CFString type.

So, in Objective-C we have
Boolean CFStringTransform ( CFMutableStringRef string, CFRange *range, CFStringRef transform, Boolean reverse );
(and in Swift)
func CFStringTransform(_ string: CFMutableString!, _ range: UnsafeMutablePointer<CFRange>, _ transform: CFString!, _ reverse: Boolean) -> Boolean

the arguments it requires are really straightforward: a string, a range in which to apply the transformation, the transformation itself and a boolean to specify whether or not use the inverse transformation.

The transformations are very powerful and range from classic Uppercase, Lowercase, Titlecase, Full/Halfwidth conversions to handling Unicode characters. We will look to a couple of examples, but for the whole list of available transformations, please check the official list

Give a name to Unicode Characters

Sometimes you need to normalize Unicode input to ascii, and since modern devices now support emoji, you can now transliterate emoji characters:
so this string: 🐝🌵💀👽

in swift we just have to do:
var str = NSMutableString(string: "🐝🌵💀👽")
CFStringTransform(str, nil, kCFStringTransformToUnicodeName, Boolean(0))

Transliterate non latin characters

From emoji to pictograms the step is easy, so we can also transliterate japanese hiragana or chinese characters to their phonetic equivalent:

var japaneseTroublesome = NSMutableString(string: "めんどくさい")
CFStringTransform(japaneseTroublesome, nil, kCFStringTransformLatinHiragana, Boolean(1))

var chineseHello = NSMutableString(string: "你好")
CFStringTransform(chineseHello, nil, kCFStringTransformMandarinLatin, Boolean(0))

for the japanese transformation note we had to use the inverse transformation since the available one is from Latin to Hiragana.

We used swift to show a couple of examples so you can easily play with it in a playground in XCode.