如何从Objective-C的NSString中获取前N个单词? [英] How to get the first N words from a NSString in Objective-C?
本文介绍了如何从Objective-C的NSString中获取前N个单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定字符串,最简单的方法是什么
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";
导致NSString带有前 N 个单词(例如10个)?
to result in an NSString with the first N (e.g., 10) words?
如果str
短于N,我还要确保它不会失败.
I'd also like to make sure it doesn't fail if the str
is shorter than N.
推荐答案
如果单词用空格分隔:
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];
然后
NSString *result = [firstWords componentsJoinedByString:@" "];
这篇关于如何从Objective-C的NSString中获取前N个单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文