Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a Russian character in NSString

I have to check out whether a russian character is present in a NSString or not.

I am using the following code for that:

NSCharacterSet * set = 
 [[NSCharacterSet characterSetWithCharactersInString:@"БГДЁЖИЙЛПФХЦЧШЩЪЫЭЮЯ"] 
   invertedSet];

BOOL check =  ([nameValue rangeOfCharacterFromSet:set].location == NSNotFound); 

return check;

But it is always returning FALSE.

Can anybody give me an idea what is wrong in my code?

Thanks

like image 1000
Rachit Avatar asked Sep 02 '12 10:09

Rachit


2 Answers

I used dasblinkenlight's answer but I included full Russian alphabet including lowercase characters:

@interface NSString (Russian)
- (BOOL)hasRussianCharacters;
@end
@implementation NSString (Russian)
- (BOOL)hasRussianCharacters{
    NSCharacterSet * set = [NSCharacterSet characterSetWithCharactersInString:@"абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"];
    return [self rangeOfCharacterFromSet:set].location != NSNotFound;
}
@end
like image 55
Shmidt Avatar answered Nov 15 '22 07:11

Shmidt


Currently, your condition checks that non-Russian (technically, non-Cyrillic) characters are absent from the string, not that Cyrillic characters are present in the string. Your code will return YES only for strings that are composed entirely of Cyrillic characters that do not have an equivalent character in the Latin alphabet1.

To fix this problem, remove the inversion, and invert the check, like this:

NSCharacterSet * set = [NSCharacterSet characterSetWithCharactersInString:@"БГДЁЖИЙЛПФХЦЧШЩЪЫЬЭЮЯ"];

return [nameValue rangeOfCharacterFromSet:set].location != NSNotFound;


1 You have forgotten to include the soft stop Ь in your list, it looks like a lower-case b, but it is not the same character.
like image 3
Sergey Kalinichenko Avatar answered Nov 15 '22 06:11

Sergey Kalinichenko