How do you detect words that start with “@” or “#” within an NSString?

前端 未结 6 1691
时光取名叫无心
时光取名叫无心 2020-12-09 21:49

I\'m building a Twitter iPhone app, and it needs to detect when you enter a hashtag or @-mention within a string in a UITextView.

How do I find all words preceded by

6条回答
  •  青春惊慌失措
    2020-12-09 22:18

    Made a category of NSString for that. It's very simple: Find all words, return all words that start with # to get the hashtags.

    Relevant code segment below - rename those methods & the category too...

    @implementation NSString (PA)
    // all words in a string
    -(NSArray *)pa_words {
        return [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    }
    
    // only the hashtags
    -(NSArray *)pa_hashTags {
        NSArray *words = [self pa_words];
        NSMutableArray *result = [NSMutableArray array];
        for(NSString *word in words) {
            if ([word hasPrefix:@"#"])
                [result addObject:word];
        }
        return result;
    }
    

提交回复
热议问题