Is there a way to work case insensitive with UITextChecker? - ios

I need my app to check if a word entered by the user is actually a real word or not. For doing this i found the UITextChecker. I am using it to check for words like this:
UITextChecker *textChecker = [[UITextChecker alloc] init];
NSLocale *locale = [NSLocale currentLocale];
NSString *language = [locale objectForKey:NSLocaleLanguageCode];
NSRange searchRange = NSMakeRange(0, [currentWord length]);
NSRange misspelledRange = [textChecker rangeOfMisspelledWordInString:currentWord range: searchRange startingAt:0 wrap:NO language:language];
if (misspelledRange.location == NSNotFound) NSLog(#"is a word");
else NSLog(#"is not a word");
This works fine until it comes to words that begin with an uppercase (and that are a lot of words in german :) ). The user is entering the text lowercase, so even if a word is actually a word it outputs "is not a word" because of it being lowercase.
I found no solution for this problem in the documentation, also i searched for it here.
So my question is if there is any better way for doing this, than transforming the first letter into an uppercase if the check failed?
Example for what i would do if there is no other way:
NSRange misspelledRange = [textChecker rangeOfMisspelledWordInString:currentWord range: searchRange startingAt:0 wrap:NO language:language];
if (misspelledRange.location == NSNotFound) NSLog(#"is a word");
else {
NSString *firstLetter = [currentWord substringToIndex:1];
NSString *restWord = [currentWord substringFromIndex:1];
currentWord = [NSString stringWithFormat:#"%#%#", [firstLetter capitalizedString], restWord];
NSRange misspelledRange = [textChecker rangeOfMisspelledWordInString:currentWord range: searchRange startingAt:0 wrap:NO language:language];
if (misspelledRange.location == NSNotFound) NSLog(#"is a word");
NSLog(#"is not a word");
}
Thanks for your help!

Related

iphone sdk : Break chinese sentence into words and letters

I have Chinese news feed and I want to break the sentence into smaller chunks to pass to the API.
How can I do it in ios? I have set character length of 50 characters for English language.
Currently I am using rangeOfString: function to find dot, comma and break into sentence.
NSString *str = nil, *rem = nil;
str = [final substringToIndex:MAX_CHAR_Private];
rem = [final substringFromIndex:MAX_CHAR_Private];
NSRange rng = [rem rangeOfString:#"?"];
if (rng.location == NSNotFound) {
rng = [rem rangeOfString:#"!"];
if (rng.location == NSNotFound) {
rng = [rem rangeOfString:#","];
if (rng.location == NSNotFound) {
rng = [rem rangeOfString:#"."];
if (rng.location == NSNotFound) {
rng = [rem rangeOfString:#" "];
}
}
}
}
if (rng.location+1 + MAX_CHAR_Private > MAXIMUM_LIMIT_Private) {
rng = [rem rangeOfString:#" "];
}
if (rng.location == NSNotFound) {
remaining = [[final substringFromIndex:MAX_CHAR_Private] retain];
}
else{
//NSRange rng = [rem rangeOfString:#" "];
str = [str stringByAppendingString:[rem substringToIndex:rng.location]];
remaining = [[final substringFromIndex:MAX_CHAR_Private + rng.location+1] retain];
}
This is not working correctly for chinese and japanese characters.
Check NSLinguisticTagger, It should work with Chinese:
From Apple: "The NSLinguisticTagger class is used to automatically segment natural-language text and tag it with information, such as parts of speech. It can also tag languages, scripts, stem forms of words, etc."
Apple documentation NSLinguisticTagger Class Reference
Also see NSHipster NSLinguisticTagger.
Also see objc.io issue 7
NSString provides that out of the box with NSStringEnumerationBySentences enumeration option:
[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
options:NSStringEnumerationBySentences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop)
{
NSString *sentence = [substring stringByTrimmingCharactersInSet:whiteSpaceSet];
// process sentence
}
];

Lookup from dictionary- objective-c

In this app I'm building, I'm hoping for the app to take a word that is given to it and search a dictionary to see whether or not the word is real. How would I go about doing this in objective-c?
Does objective-c have anything like the 'V-Lookup' function in Excel? If so, would this be useful?
Any help is appreciated!
So what you're trying to do is this:
iPhone objective-c: detecting a 'real' word
-(BOOL)isDictionaryWord:(NSString*)word {
UITextChecker *checker = [[UITextChecker alloc] init];
NSLocale *currentLocale = [NSLocale currentLocale];
NSString *currentLanguage = [currentLocale objectForKey:NSLocaleLanguageCode];
NSRange searchRange = NSMakeRange(0, [word size]];
NSRange misspelledRange = [checker rangeOfMisspelledWordInString:word range: searchRange startingAt:0 wrap:NO language: currentLanguage ];
return misspelledRange.location == NSNotFound;
}

Below UITextChecker Function Is Not Working Properly

NSString * currentWord;
currentWord = Text.text;
UITextChecker* checker = [[UITextChecker alloc] init];
NSString* preferredLanguage = [[UITextChecker availableLanguages] objectAtIndex:0];
NSRange range;
range = [checker rangeOfMisspelledWordInString:currentWord
range:NSMakeRange(0, [currentWord length])
startingAt:0
wrap:NO
language:preferredLanguage];
if (range.location == NSNotFound)
{
NSLog(#"Word found");
}
else
{
NSLog(#"Word not found");
}
//Here i used UITextChecker Function ,even for the wrong word, the above function shows correct word statement
eg: wrong word like abcd,
bcde,
cdef,
CAPs, kindly help me what is the reason behind this. Is there any other option to solve this?
Thanks in advance
UITextChecker *Checker = [[UITextChecker alloc] init];
NSRange range = NSMakeRange(0, inputWord.length);
NSRange misspelledRange = [Checker rangeOfMisspelledWordInString:[Sentence lowercaseString] range:range startingAt:0 wrap:NO language:#"en_IN"];
bool isValidWord = misspelledRange.location == NSNotFound;
//NSLog(#"----%i", misspelledRange.location);
if (isValidWord)
{
isValidWord = [self checkIfWordExistsInSuggestedSpellings:Sentence];
NSLog(#"++++%d", isValidWord);
}
return isValidWord;
}
else
{
NSLog(#"Invalid word");
return false;
}
NSNotFound means that whatever you asked for wasn't found. == is equality operator. Your code prints "Word found" when range.location is equal to NSNotFound.

How do I get the substring between braces?

I have a string as this.
NSString *myString = #"{53} balloons";
How do I get the substring 53 ?
NSString *myString = #"{53} balloons";
NSRange start = [myString rangeOfString:#"{"];
NSRange end = [myString rangeOfString:#"}"];
if (start.location != NSNotFound && end.location != NSNotFound && end.location > start.location) {
NSString *betweenBraces = [myString substringWithRange:NSMakeRange(start.location+1, end.location-(start.location+1))];
}
edit: Added range check, thx to Keab42 - good point.
Here is what I did.
NSString *myString = #"{53} balloons";
NSCharacterSet *delimiters = [NSCharacterSet characterSetWithCharactersInString:#"{}"];
NSArray *splitString = [myString componentsSeparatedByCharactersInSet:delimiters];
NSString *substring = [splitString objectAtIndex:1];
the substring is 53.
For Swift 4.2:
if let r1 = string.range(of: "{")?.upperBound,
let r2 = string.range(of: "}")?.lowerBound {
print (String(string[r1..<r2]))
}
You can use a regular expression to get the number between the braces. It might seem a bit complicated but the plus side is that it will find multiple numbers and the position of the number doesn't matter.
Swift 4.2:
let searchText = "{53} balloons {12} clowns {123} sparklers"
let regex = try NSRegularExpression(pattern: "\\{(\\d+)\\}", options: [])
let matches = regex.matches(in: searchText, options: [], range: NSRange(searchText.startIndex..., in: searchText))
matches.compactMap { Range($0.range(at: 1), in: searchText) }
.forEach { print("Number: \(searchText[$0])") }
Objective-C:
NSString *searchText = #"{53} balloons {12} clowns {123} sparklers";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\\{(\\d+)\\}"
options:0
error:nil];
NSArray *matches = [regex matchesInString:searchText
options:0
range:NSMakeRange(0, searchText.length)];
for (NSTextCheckingResult *r in matches)
{
NSRange numberRange = [r rangeAtIndex:1];
NSLog(#"Number: %#", [searchText substringWithRange:numberRange]);
}
This will print out:
Number: 53
Number: 12
Number: 123
Try this code.
NSString *myString = #"{53} balloons";
NSString *value = [myString substringWithRange:NSMakeRange(1,2)];
For Swift 2.1 :-
var start = strData?.rangeOfString("{")
var end = strData?.rangeOfString("}")
if (start!.location != NSNotFound && end!.location != NSNotFound && end!.location > start!.location) {
var betweenBraces = strData?.substringWithRange(NSMakeRange(start!.location + 1, end!.location-(start!.location + 1)))
print(betweenBraces)
}
I guess, your a looking for the NSScanner class, at least if you are addressing a general case. Have a look in Apples documentation.
Search the location for "{" and "}".
Take substring between those index.
Checked with any number of data:
NSString *str = #"{53} balloons";
NSArray* strary = [str componentsSeparatedByString: #"}"];
NSString* str1 = [strary objectAtIndex: 0];
NSString *str2 = [str1 stringByReplacingOccurrencesOfString:#"{" withString:#""];
NSLog(#"number = %#",str2);
Another method is
NSString *tmpStr = #"{53} balloons";
NSRange r1 = [tmpStr rangeOfString:#"{"];
NSRange r2 = [tmpStr rangeOfString:#"}"];
NSRange rSub = NSMakeRange(r1.location + r1.length, r2.location - r1.location - r1.length);
NSString *subString = [tmpStr substringWithRange:rSub];
If you don't know how many digits there will be, but you know it will always be enclosed with curly braces try this:
NSString *myString = #"{53} balloons";
NSRange startRange = [myString rangeOfString:#"{"];
NSRange endRange = [myString rangeOfString:#"}"];
if (startRange.location != NSNotFound && endRange.location != NSNotFound && endRange.location > startRange.location) {
NSString *value = [myString substringWithRange:NSMakeRange(startRange.location,endRange.ocation - startRange.location)];
}
There's probably a more efficient way to do it though.

How to get NSRange(s) for a substring in NSString? [duplicate]

This question already has answers here:
How to get all NSRange of a particular character in a NSString?
(4 answers)
Closed 9 years ago.
NSString *str = #" My name is Mike, I live in California and I work in Texas. Weather in California is nice but in Texas is too hot...";
How can I loop through this NSString and get NSRange for each occurrence of "California", I want the NSRange because I would like to change it's color in the NSAttributed string.
NSRange range = NSMakeRange(0, _stringLength);
while(range.location != NSNotFound)
{
range = [[attString string] rangeOfString: #"California" options:0 range:range];
if(range.location != NSNotFound)
{
range = NSMakeRange(range.location + range.length, _stringLength - (range.location + range.length));
[attString addAttribute:NSForegroundColorAttributeName value:_green range:range];
}
}
Lots of ways of solving this problem - NSScanner was mentioned; rangeOfString:options:range etc. For completeness' sake, I'll mention NSRegularExpression. This also works:
NSMutableAttributedString *mutableString = nil;
NSString *sampleText = #"I live in California, blah blah blah California.";
mutableString = [[NSMutableAttributedString alloc] initWithString:sampleText];
NSString *pattern = #"(California)";
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
// enumerate matches
NSRange range = NSMakeRange(0,[sampleText length]);
[expression enumerateMatchesInString:sampleText options:0 range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSRange californiaRange = [result rangeAtIndex:0];
[mutableString addAttribute:NSForegroundColorAttributeName value:[NSColor greenColor] range:californiaRange];
}];
with
[str rangeOfString:#"California"]
and
[str rangeOfString:#"California" options:YOUR_OPTIONS range:rangeToSearch]
You may use rangeOfString:options:range: or NSScanner (there are other possibilities like regexps but anyway). It's easier to use first approach updating range, i.e. search for first occurrence and then depending on the result update the search range. When the search range is empty, you've found everything;

Resources