Search code examples
iosobjective-cspecial-characters

Allowing special characters in iOS


I am allowing the user to input some data into the TextField. The user inputs Š1234D into the TextField.

The code I have looks like this:

NSString *string = textField.text;
for (int nCtr = 0; nCtr < [string length]; nCtr++) {
                const char chars = [string characterAtIndex:nCtr];
                int isAlpha = isalpha(chars);
}

string output looks like this:Š1234D Then I printed the first chars value, it looks like this:'`' instead of 'Š'. Why is this so? I would like to allow special characters in my code as well.

Any suggestion would be welcome as well. Need some guidance. Thanks


Solution

  • You are truncating the character value as [NSString chatacterAtIndex:] returns unichar (16-bit) and not char (8-bit). try:

    unichar chars = [string characterAtIndex:nCtr];
    

    UPDATE: Also note that you shouldn't be using isalpha() to test for letters, as that is restricted to Latin character sets and you need something that can cope with non-latin characters. Use this code instead:

    NSCharacterSet *letterSet = [NSCharacterSet letterCharacterSet];
    NSString *string = textField.text;
    for (NSUIntger nCtr = 0; nCtr < [string length]; nCtr++)
    {
        const unichar c = [string characterAtIndex:nCtr];
        BOOL isAlpha = [letterSet characterIsMember:c];
        ...
    }