2

I'm converting Russian (or any language) string to a good looking Latin string to use in URL like example.com/obezd-pedestala

I use this code:

CFMutableStringRef bufferRef = (__bridge CFMutableStringRef)buffer;
CFStringTransform(bufferRef, NULL, kCFStringTransformToLatin, false);
CFStringTransform(bufferRef, NULL, kCFStringTransformStripCombiningMarks, false);
CFStringTransform(bufferRef, NULL, kCFStringTransformStripDiacritics, false);

If I pas string like buffer Объезд пьедестала, I get Obʺezd pʹedestala. Letter ъ is replaced by ʺ and ь is replaced by ʹ.

I can use stringByAddingPercentEscapesUsingEncoding to get a valid URL of course, but this is not a good looking URL I want.

How can I remove all those quotes and god knows what else characters from resulting string?

1 Answer 1

5

The docs for CFStringTransform() note that it can take "any valid ICU transform ID defined in the ICU User Guide for Transforms". From that and a bit of knowledge about Unicode categories, I came up with the following, which will strip such odd characters from the string:

CFStringTransform(bufferRef, NULL, CFSTR("[^[:Latin:][:space:][:number:]] Remove"), false);

Apparently, kCFStringTransformToLatin does not leave only characters in the Latin category. The above transform removes any character which is not in the union of the Latin, space, and number categories. You could customize that further with different character sets if you have different needs.

7
  • Wow, CFStringTransform is really powerful. Thank you. Is there a list of available transliterator identifiers?
    – ksoftware
    Dec 30, 2014 at 5:34
  • How can I leave numbers in my string for example?
    – ksoftware
    Dec 30, 2014 at 5:48
  • Oh. I originally had a solution to leave numbers, but I reworked things and forgot that. I'll edit my answer. Dec 30, 2014 at 7:11
  • 1
    In my answer, the only "transliterator" is Remove. For others, see here (includes both the general transforms and the script transforms). The other part, in the brackets, is a filter controlling which characters are affected. I'm using Unicode character properties, including categories. Dec 30, 2014 at 7:24
  • Have you managed to get list of available transliterators IDs using Corefoundation API? Since some of transliterator usages expected an exception before passing string to transliterator engine, that could be a way of validate ID
    – ugene
    Jul 9, 2015 at 14:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.