问题
Hello i have a problem that i don't know how to solve. The problem is that I even don't know how to google about it. I've already spent hours on the internet finding the solution, but didn't succeeded. The situation is like this:
I have String, lets say:
NSString *string = @"aąbcčdeęėfghiįjzž";
my result has to be like this:
NSString *string = @"aabccdeeefghiujzz";
So if you understood i have to do this:
replace ą with a
replace č with c
replace ė with e
replace ę with e
and so on..
Maybe anyone could help me? i have an answer but it's not very optimized, i am hoping for some more convenient solution.
Thanks in advance!
回答1:
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
回答2:
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).
回答3:
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];
回答4:
I can offer only this:
[string stringByReplacingOccurrencesOfString:@"ą" withString:@"a"];
and so on...
来源:https://stackoverflow.com/questions/10739076/replace-letters-in-a-string