Pierre
Pierre

Reputation: 11633

NSString replace unicode characters

I'w working with a server and I have to download text to my iOS application. Only problem : all characters like "é à ç" are replaced by "\U008" for example. Is there a way to fix this problem, to replace this code by the right character ?

Upvotes: 3

Views: 6157

Answers (3)

Constantin Saulenco
Constantin Saulenco

Reputation: 2383

You can get character buffer and validate each character like so:

- (NSString *) removeUnicode:(NSString *) unicodeString {
    NSUInteger len = [unicodeString length];
    unichar buffer[len+1];

    [unicodeString getCharacters:buffer range:NSMakeRange(0, len)];

    unichar okBuffer[len+1];
    int index = 0;
    for(int i = 0; i < len; i++) {
        if(buffer[i] < 128) {
            okBuffer[index] = buffer[i];
            index = index + 1;
        }
    }

    NSString *removedUnicode = [[NSString alloc] initWithCharacters:okBuffer length:index];

    return removedUnicode;
}

or you can use this sample:

NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:[NSCharacterSet alphanumericCharacterSet]] invertedSet];
stringWithOutUnicode = [[stringWithUnicode componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:@""];

and you can create your own valid character set and get not allowed characters

NSString *allowedCharacters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString: allowedCharacters] invertedSet];

Upvotes: 0

HeltonRosa
HeltonRosa

Reputation: 11

I tested some encodings and NSMacOSRomanStringEncoding fit well.

My test was:

NSString *encodedString = [NSString stringWithCString:"Você realmente deseja sair da área restrita" encoding:NSMacOSRomanStringEncoding];

Remember that the message has to be a C-string ("string") and not an NSString(@"string")

Upvotes: 1

Matteo Alessani
Matteo Alessani

Reputation: 10412

Try to parse the received text (textToParse variable) with this one:

NSString *encodedString = textToParse;
NSString *decodedString = [NSString stringWithUTF8String:[encodedString cStringUsingEncoding:[NSString defaultCStringEncoding]]];

Upvotes: 4

Related Questions