Detect Language of NSString

There is API in cocoa available to check the language of a string, and it is always best to use Foundation over CoreFoundation whenever possible.

NSArray *tagschemes = [NSArray arrayWithObjects:NSLinguisticTagSchemeLanguage, nil];
NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes:tagschemes options:0];
[tagger setString:@"Das ist ein bisschen deutscher Text. Bitte löschen Sie diesen nicht."];
NSString *language = [tagger tagAtIndex:0 scheme:NSLinguisticTagSchemeLanguage tokenRange:NULL sentenceRange:NULL];

Alternatively, if you happen to have mixed language text, you can use the enumerateLinguisticTagsInRange API to get the language of each word in the text.

Leave a Comment