6

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

Alex Cio
  • 6,014
  • 5
  • 44
  • 74
Rachit
  • 1,159
  • 3
  • 13
  • 23

2 Answers2

5

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
Shmidt
  • 16,436
  • 18
  • 88
  • 136
3

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.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • @Shmidt That was an incorrect edit: the OP excluded all Russian characters that resemble Latin characters on purpose, not by mistake. – Sergey Kalinichenko Jul 26 '13 at 13:15
  • @dasblinkenlight I didn't see anything in text about purpose, so I think it was a mistake — some Russian characters look like Latin but it's not Latin. Subject of the post says only about Russian, so some users can be confused with this answer. Anyway I created my own for them. – Shmidt Jul 26 '13 at 13:39