Replace letters in a string

*爱你&永不变心* 提交于 2019-11-29 14:29:36

Let the frameworks do the conversion for you:

NSString *blah = @"aąbcčdeęėfghiįjzž";
NSData *data = [blah dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *newblah = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"new: %@", newblah);

This logs:

new: aabccdeeefghiijzz

This will work:

NSString *str = @"aąbcčdeęėfghiįjzž";
NSLog(@"%@", str);
NSMutableString *s = [[str decomposedStringWithCompatibilityMapping] mutableCopy];
NSUInteger pos = 0;
while(pos < s.length) {
    NSRange r = [s rangeOfComposedCharacterSequenceAtIndex:pos];
    if (r.location == NSNotFound) break;
    pos = ++r.location;
    if (r.length == 1) continue;
    r.length--;
    [s deleteCharactersInRange:r];
}
NSLog(@"%@", s);

The idea is to first decompose each character with diacritical mark into a sequence of its base character and a sequence of Unicode combining diacritical marks (that's done by decomposedStringWithCompatibilityMapping), then go through the string, and remove all such marks one by one (that's what the loop does).

Dave DeLong answer will replace "æ" with "ae" and "ß" with "s", but won't replace ligatures œ, ij, ff, fi, fl, ffi, ffl, ſt, st, ...

An improved solution is to add three lines of mapping to handle everything fine:

blah = [blah stringByReplacingOccurrencesOfString:@"Œ" withString:@"OE"];
blah = [blah stringByReplacingOccurrencesOfString:@"œ" withString:@"oe"];
blah = [blah precomposedStringWithCompatibilityMapping];

NSData *data = [blah dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *newblah = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

I can offer only this:

[string stringByReplacingOccurrencesOfString:@"ą" withString:@"a"];

and so on...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!