给出一个字符串是最简单的方法:
NSString *str = @"Some really really long string is here and I just want the first 10 words,for example";
导致具有前N个(例如10个)词的NSString?
编辑:如果str比N.短,我也想确保它不会失败.
解决方法
如果这些单词是空格分隔的:
NSInteger nWords = 10; NSRange wordRange = NSMakeRange(0,nWords); NSArray *firstWords = [[str componentsSeparatedByString:@" "] subarrayWithRange:wordRange];
如果你想打破所有的空白:
NSCharacterSet *delimiterCharacterSet = [NSCharacterSet whitespaceAndNewlineCharacterSet]; NSArray *firstWords = [[str componentsSeparatedByCharactersInSet:delimiterCharacterSet] subarrayWithRange:wordRange];
然后,
NSString *result = [firstWords componentsJoinedByString:@" "];