什麼是最簡單的方式,給定的字符串:如何從Objective-C的NSString中獲取前N個單詞?
NSString *str = @"Some really really long string is here and I just want the first 10 words, for example";
導致一個NSString與第一Ñ(例如,10)個字?
編輯:我也想確保,如果str
大於N.
什麼是最簡單的方式,給定的字符串:如何從Objective-C的NSString中獲取前N個單詞?
NSString *str = @"Some really really long string is here and I just want the first 10 words, for example";
導致一個NSString與第一Ñ(例如,10)個字?
編輯:我也想確保,如果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:@" "];
儘管Barry Wark的代碼適用於英語,但它不是檢測單詞分隔符的首選方式。許多語言(如中文和日文)不會使用空格分隔單詞。例如,德國有許多化合物難以正確分離。
要使用什麼是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);
基於巴里的回答,我寫了一個函數爲這個頁面的緣故(仍然給他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:@" "];
}
這裏的我的解決方案,從這裏給出的答案派生,對於我自己的問題,從字符串中刪除第一個單詞...
NSMutableArray *words = [NSMutableArray arrayWithArray:[lowerString componentsSeparatedByString:@" "]];
[words removeObjectAtIndex:0];
return [words componentsJoinedByString:@" "];
你打敗了我:+1。不要忘記componentsJoinedByString:因爲OP正在尋找一個NSString結果:) – 2009-11-18 01:03:36
如果字符串只有3個字,這是否工作?什麼是wordIndexes? (它在第一個示例中似乎未使用) – philfreo 2009-11-18 01:40:29
如果只有三個單詞,則必須更改nWords。當然,您可以在決定nWords之前找到componentsSeparatedByString並計算它們,但是您沒有在您的問題中提到這一點。 – 2009-11-18 01:56:00