0

I am looking for an Objective-C method that will find a specific word within a string. I was using:

- (NSRange)rangeOfString:(NSString *)aString

but it's not doing exactly what I want. The reason why is that I am looking more for a token match than finding the word itself. I am working with attributed strings and I need specific parts of a string to have attributes. The parts that need the attributes must be equal to the contents of an object. The problem that I'm running into is that if I have an object with the contents 'star', but the word 'stars' is also in the string, the range method will just return the range of 'star' and leave the s, rather than determining if the exact word 'star' exists within the string.

I'm not sure if that kind of method exists, but I would greatly appreciate any help! If you need any other clarification please let me know!

edit: To help out a little bit I will give you my exact situation:

I have a card game that matches 3 cards. For this example let's say that the card has a ■ on it. No two cards are the same. Selecting cards in an order like '■■', '■■■', and '■■', will result in the problem. Like I said the contents need to be attributed. The problem is that since there are 2 cards that have '■■' on it and one with '■■■', the attributes are placed on the first '■■' fine, but then the '■■■' card get's placed with the '■■' cards attributes on it's first 2 squares and the final '■■' card never gets anything placed on it. So the issue is that it's finding the first substring of '■■' even though it's apart of a larger word. I need it to only look at words/tokens within the string that match the contents exactly.

Jano
  • 62,815
  • 21
  • 164
  • 192
BlueBear
  • 7,469
  • 6
  • 32
  • 47

2 Answers2

1

Seems like a feasible task for regular expressions (very rare bird!):

NSRange token = [string rangeOfString:@"\\bstar\\b" options:NSRegularExpressionSearch];
  • I did look at that method, but I was unsure if it would be able to help this situation. I did an edit to the original post to give some additional clarity on my situation. – BlueBear Jul 16 '13 at 21:09
0

You can turn an attributed string into a regular string with [attributedString string] and proceed as usual with NSStringEnumerationByWords. Example, given ...stars...star... it should return star but not stars.

[[s string] enumerateSubstringsInRange:NSMakeRange(0, [s length])
                      options:NSStringEnumerationByWords
                   usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
    if ([substring isEqualToString:@"star"]){
       NSLog(@"%@", substring);
       *stop = YES;
    }
}];

(not sure if I understood your card example correctly)

Jano
  • 62,815
  • 21
  • 164
  • 192