Comment get NSRange (s) pour une sous-string dans NSSsortingng?

NSSsortingng *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..."; 

Comment puis-je faire une boucle sur ce NSSsortingng et get NSRange pour chaque occurrence de "Californie", je veux le NSRange parce que je voudrais changer sa couleur dans la string NSAtsortingbuted.

  NSRange range = NSMakeRange(0, _ssortingngLength); while(range.location != NSNotFound) { range = [[attSsortingng ssortingng] rangeOfSsortingng: @"California" options:0 range:range]; if(range.location != NSNotFound) { range = NSMakeRange(range.location + range.length, _ssortingngLength - (range.location + range.length)); [attSsortingng addAtsortingbute:NSForegroundColorAtsortingbuteName value:_green range:range]; } } 

Beaucoup de façons de résoudre ce problème – NSScanner été mentionné; rangeOfSsortingng:options:range etc. Par souci d'exhaustivité, je mentionnerai NSRegularExpression . Cela fonctionne aussi:

  NSMutableAtsortingbutedSsortingng *mutableSsortingng = nil; NSSsortingng *sampleText = @"I live in California, blah blah blah California."; mutableSsortingng = [[NSMutableAtsortingbutedSsortingng alloc] initWithSsortingng:sampleText]; NSSsortingng *pattern = @"(California)"; NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil]; // enumerate matches NSRange range = NSMakeRange(0,[sampleText length]); [expression enumerateMatchesInSsortingng:sampleText options:0 range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { NSRange californiaRange = [result rangeAtIndex:0]; [mutableSsortingng addAtsortingbute:NSForegroundColorAtsortingbuteName value:[NSColor greenColor] range:californiaRange]; }]; 

avec

 [str rangeOfSsortingng:@"California"] 

et

 [str rangeOfSsortingng:@"California" options:YOUR_OPTIONS range:rangeToSearch] 

Vous pouvez utiliser rangeOfSsortingng: options: range: ou NSScanner (il existe d'autres possibilités comme les regexps mais de toute façon). Il est plus facile d'utiliser la plage de mise à jour de la première approche, c.-à-d. De searchr la première occurrence et ensuite, en fonction du résultat, de mettre à jour la plage de search. Lorsque la plage de search est vide, vous avez tout trouvé.