How to get the first N words from a NSString in Objective-C?

后端 未结 4 1415
无人及你
无人及你 2020-12-08 06:14

What\'s the simplest way, given a string:

NSString *str = @\"Some really really long string is here and I just want the first 10 words, for example\";
         


        
4条回答
  •  孤街浪徒
    2020-12-08 06:36

    Based on Barry's answer, I wrote a function for the sake of this page (still giving him credit on SO)

    + (NSString*)firstWords:(NSString*)theStr howMany:(NSInteger)maxWords {
    
        NSArray *theWords = [theStr componentsSeparatedByString:@" "];
        if ([theWords count] < maxWords) {
            maxWords = [theWords count];
        }
        NSRange wordRange = NSMakeRange(0, maxWords - 1);
        NSArray *firstWords = [theWords subarrayWithRange:wordRange];       
        return [firstWords componentsJoinedByString:@" "];
    }
    

提交回复
热议问题