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

我与影子孤独终老i 提交于 2019-11-28 05:08:27
Barry Wark

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:@" "];
sbooth

While Barry Wark's code works well for English, it is not the preferred way to detect word breaks. Many languages, such as Chinese and Japanese, do not separate words using spaces. And German, for example, has many compounds that are difficult to separate correctly.

What you want to use is CFStringTokenizer:

CFStringRef string; // Get string from somewhere
CFLocaleRef locale = CFLocaleCopyCurrent();

CFStringTokenizerRef tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault, string, CFRangeMake(0, CFStringGetLength(string)), kCFStringTokenizerUnitWord, locale);

CFStringTokenizerTokenType tokenType = kCFStringTokenizerTokenNone;
unsigned tokensFound = 0, desiredTokens = 10; // or the desired number of tokens

while(kCFStringTokenizerTokenNone != (tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer)) && tokensFound < desiredTokens) {
  CFRange tokenRange = CFStringTokenizerGetCurrentTokenRange(tokenizer);
  CFStringRef tokenValue = CFStringCreateWithSubstring(kCFAllocatorDefault, string, tokenRange);

  // Do something with the token
  CFShow(tokenValue);

  CFRelease(tokenValue);

  ++tokensFound;
}

// Clean up
CFRelease(tokenizer);
CFRelease(locale);

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:@" "];
}

Here's my solution, derived from the answers given here, for my own problem of removing the first word from a string...

NSMutableArray *words = [NSMutableArray arrayWithArray:[lowerString componentsSeparatedByString:@" "]];
[words removeObjectAtIndex:0];
return [words componentsJoinedByString:@" "];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!