lakshmen
lakshmen

Reputation: 29064

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

Upvotes: 1

Views: 1066

Answers (2)

Sulthan
Sulthan

Reputation: 130092

characterAtIndex: returns a unichar (2-byte Unicode character), not char (1-byte ASCII character). By casting it to char, you are getting only one of the two bytes.

You should turn on your compiler warnings. I believe "Suspicious implicit conversions" should do the trick.

On a separate note, you can't use isAlpha(char) with a unichar. Use [[NSCharacterSet letterCharacterSet] characterIsMember:chars]

Upvotes: 3

trojanfoe
trojanfoe

Reputation: 122391

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];
    ...
}

Upvotes: 3

Related Questions