Rachit
Rachit

Reputation: 1189

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

Upvotes: 6

Views: 1556

Answers (2)

Shmidt
Shmidt

Reputation: 16674

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

Upvotes: 5

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

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.

Upvotes: 3

Related Questions