简体   繁体   中英

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

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM