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

后端 未结 4 1410
无人及你
无人及你 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:48

    If the words are space-separated:

    NSInteger nWords = 10;
    NSRange wordRange = NSMakeRange(0, nWords);
    NSArray *firstWords = [[str componentsSeparatedByString:@" "] subarrayWithRange:wordRange];
    

    if you want to break on all whitespace:

    NSCharacterSet *delimiterCharacterSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSArray *firstWords = [[str componentsSeparatedByCharactersInSet:delimiterCharacterSet] subarrayWithRange:wordRange];
    

    Then,

    NSString *result = [firstWords componentsJoinedByString:@" "];
    

提交回复
热议问题