How do i find range of locations of a specific word in a sentence in objective c?
Lets say i have the following NSString
NSString *stringOfHashTags = "mr#hello Mr.#hello"
I am using
NSString word=@"hello";
NSRange termsRange = [stringOfHashTags rangeOfString:[word substringFromIndex:[word rangeOfString:@"#"].location]];
to find the location of a word that starts with # but if the word exists two or more times in the sentence it only returns the first location. Any help appreciated.
CodePudding user response:
You can use enumerateSubstringsInRange (searching and reading documentation is always the starting point).
Simple example:
NSString *aString = @"mr#hello Mr.#hello";
NSString *word = @"hello";
[aString enumerateSubstringsInRange:NSMakeRange(0, [aString length])
options:NSStringEnumerationByWords | NSStringEnumerationLocalized
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){
if ([substring rangeOfString:word options:NSCaseInsensitiveSearch].location != NSNotFound) {
/* do whatever */;
NSLog(@"found at: %@ / %@", [NSValue valueWithRange:substringRange], [NSValue valueWithRange:enclosingRange]);
}
}];
debug console output:
proj[64417:6900139] found at: NSRange: {3, 5} / NSRange: {3, 6}
proj[64417:6900139] found at: NSRange: {13, 5} / NSRange: {13, 5}
Edit
If you want to find all words that begin with #
in a string such as:
"this #is a #test of #88 including embedded #tags such as Mr.#tags. #Is that #what you're looking #for?"
as opposed to finding multiple occurrences of a word (as in your question), you likely want to use Regular Expressions.
Another quick, simple example:
NSString *searchedString = @"this #is a #test of #88 including embedded #tags such as Mr.#tags. #Is that #what you're looking #for?";
NSRange searchedRange = NSMakeRange(0, [searchedString length]);
// searching for any Word that begins with #
NSString *pattern = @"\\#\\w ";
NSError *error = nil;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern: pattern options:0 error:&error];
if (error) {
NSLog(@"Could not create regex!!!");
return;
}
NSArray *matches = [regex matchesInString:searchedString options:0 range: searchedRange];
for (NSTextCheckingResult *match in matches) {
NSString *matchText = [searchedString substringWithRange:[match range]];
NSLog(@"match: %@", matchText);
}
debug console output:
proj[66898:6935236] match: #is
proj[66898:6935236] match: #test
proj[66898:6935236] match: #88
proj[66898:6935236] match: #tags
proj[66898:6935236] match: #tags
proj[66898:6935236] match: #Is
proj[66898:6935236] match: #what
proj[66898:6935236] match: #for
Edit 2
Your second comment really should be a new post, as it's an entirely different question (about RegEx syntax).
But, to get you on your way...
NSString *searchedString = @"These #tags, with #various& #excluded! #chars. And #other@ formats #88 including #emo