46

I want to change a sentence, for example:

Être ou ne pas être. C'était là-bas.

Would become:

Etre ou ne pas etre. C'etait la-bas.

Is there any easy way to do this with NSString? Or do I have to develop this on my own by checking each char?

8 Answers 8

60
NSString *str = @"Être ou ne pas être. C'était là-bas.";
NSData *data = [str dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *newStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"%@", newStr);

... or try using NSUTF8StringEncoding instead.

List of encoding types here:

https://developer.apple.com/documentation/foundation/nsstringencoding


Just FTR here's a one line way to write this great answer:

yourString = [[NSString alloc]
  initWithData:
    [yourString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]
  encoding:NSASCIIStringEncoding];
8
  • 2
    Thank you but when I transform UTF-8 characters, for example à doesn't become a but ?.
    – Rob
    Jun 7, 2012 at 13:17
  • Edited post - sorry I used the wrong encoding type. My version using ASCII encoding works in Xcode - maybe using the correct encoding will work for you.
    – Luke
    Jun 7, 2012 at 13:20
  • 3
    This seems to assume that strings can be converted to ASCII without losing information (other than accents). It might work for the example but is far from guaranteed to work when using languages in other character sets.
    – Rupert
    May 6, 2014 at 14:11
  • 1
    @vomako The string you're converting to data is probably nil - the code works fine under iOS 8.
    – Luke
    Feb 23, 2015 at 21:43
  • 1
    @vomako If you cannot solve the issue (use Google and this site!), then I'd recommend making a new question on here, and link to this one and your comments for reference.
    – Luke
    Feb 24, 2015 at 11:56
49

Mattt Thompson covered this in NSHipster and again at WWDC 2013 session 228

TL;DR

NSMutableString *str = [@"Être ou ne pas être. C'était là-bas." mutableCopy];
CFStringTransform((__bridge CFMutableStringRef)string, NULL, kCFStringTransformStripCombiningMarks, NO);

Should do the trick, it worked great for me.

Caveat Since a lot of people in the comments say this should be the accepted answer I want to give a caveat for this method. This method is pretty damn slow and should be used with care if huge amounts of string/data needs to be transformed

7
  • 2
    This question is the second I found which has the 'trick' to convert to NSData and back as the accepted answer. Your answer should be the accepted one, it even beats [input stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]]; in that it does not require a locale.
    – xorgate
    Nov 5, 2013 at 6:56
  • Thanks, turns out theres a lot of cool stuff in Core Foundation that gets over looked
    – tapi
    Mar 26, 2014 at 15:19
  • Should be the approved answer, and thanks for the link to Mattt Thompson's page.
    – lucasart
    Apr 9, 2014 at 1:58
  • I agree - this is a much more reliable answer.
    – Rupert
    May 6, 2014 at 14:11
  • Note also that the string has to be a NSMutableString, not a NSString*. May 31, 2014 at 13:50
28

Have you tried

[string stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]]

or

Boolean CFStringTransform (
   CFMutableStringRef string,
   CFRange *range,
   CFStringRef transform,
   Boolean reverse
);

?

CFStringTransform & Transform Identifiers

NSMutableString *string = ...;
CFMutableStringRef stringRef = (__bridge CFMutableStringRef)string;
CFStringTransform(stringRef, NULL, kCFStringTransformToLatin, NO);
NSLog(@"%@", string);
2
  • See changed answer for solution without the need for intermediate NSData conversion and UTF-8 encoding loss.
    – Regexident
    Jun 7, 2012 at 13:26
  • @Regexident I tried this but it didn't work i'm getting error on CFStringTransform(stringRef, NULL, kCFStringTransformToLatin, NO); this line...
    – Karthik
    Apr 17, 2013 at 6:06
16

Just an update to say that it can be done like that in swift:

"Être ou ne pas être. C'était là-bas.".stringByFoldingWithOptions(NSStringCompareOptions.DiacriticInsensitiveSearch, locale: NSLocale.currentLocale())

--> "Etre ou ne pas etre. C'etait la-bas."

1
  • Superb answer, and great to see more Swift variations.
    – SaltyNuts
    Apr 15, 2015 at 17:51
9

Here a Performance Test using Swift 2.0 on iPhone 6 iOS 9.0 Simulator between solutions using:

  • CFStringTransform (Task 1)
  • stringByFoldingWithOptions (Task 2)

Task 2 is consistently faster, e.g.:

Task 1 took 9.49736100435257 seconds.
Task 2 took 1.96649599075317 seconds.

Here the test:

    let timer = ParkBenchTimer()
    for _ in 1...1000000 {
        let mStringRef = NSMutableString(string: "Être ou ne pas être. C'était là-bas.") as CFMutableStringRef
        CFStringTransform(mStringRef, nil, kCFStringTransformStripCombiningMarks, false)
        String(mStringRef)
    }
    print("Task 1 took \(timer.stop()) seconds.")

    let timer2 = ParkBenchTimer()
    for _ in 1...1000000 {
        "Être ou ne pas être. C'était là-bas.".stringByFoldingWithOptions(NSStringCompareOptions.DiacriticInsensitiveSearch, locale: NSLocale.currentLocale())
    }
    print("Task 2 took \(timer2.stop()) seconds.")

ParkBenchTimer by Klaas: https://stackoverflow.com/a/26578191/1097106

1
  • Thanks for answering my question on the performance comparison between the two methods ! Dec 27, 2016 at 14:51
6

Swift 3 (tested in playground)

//String+StripCombiningMarks.swift

extension String {
    /// strip combining marks (accents or diacritics)
    var stripCombiningMarks: String {
        let mStringRef = NSMutableString(string: self) as CFMutableString
        CFStringTransform(mStringRef, nil, kCFStringTransformStripCombiningMarks, false)
        return mStringRef as String
    }
}

Usage:

let umlaut = "äöüÄÖÜ"
let stripped = umlaut.stripCombiningMarks //aouAOU
3

here is complete code. use function stringbyfoldignWithOptions.

NSString *str1=@"Être ou ne pas être C'était là-bas"; NSString *str2=[str1 stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale systemLocale]]; NSLog(@"%@",str2);

1

For those who want a Swift version of CFStringTransform solution:

let stripAccentAndDiacritics: (String) -> String = {
    var mStringRef = NSMutableString(string: $0) as CFMutableStringRef
    CFStringTransform(mStringRef, nil, kCFStringTransformStripCombiningMarks, Boolean(0))
    return String(mStringRef)
}

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.