2013-03-12 66 views
1

去除第一N個字如何從一個NSString刪除單詞的第N個?的iOS從一個NSString

比如......「我去商店買牛奶。」我想刪除第三個字,使其...

「的商店買牛奶。」 (注意,'''之前沒有空格)。

謝謝!

回答

3

這個問題可以表述爲:「我怎樣才能得到一個子開始在字符串中的第4個字?」,這是稍微容易解決。我在這裏也假定,少於4個字的字符串應該變空。

不管怎樣,主力這裏是-enumerateSubstringsInRange:options:usingBlock:,我們可以用它來找到第4個字。

NSString *substringFromFourthWord(NSString *input) { 
    __block NSUInteger index = NSNotFound; 
    __block NSUInteger count = 0; 
    [input enumerateSubstringsInRange:NSMakeRange(0, [input length]) options:(NSStringEnumerationByWords|NSStringEnumerationSubstringNotRequired) usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { 
     if (++count == 4) { 
      // found the 4th word 
      index = substringRange.location; 
      *stop = YES; 
     } 
    }]; 
    if (index == NSNotFound) { 
     return @""; 
    } else { 
     return [input substringFromIndex:index]; 
    } 
} 

這種方式的工作方式是我們要求-enumerateSubstrings...用文字來枚舉。當我們找到第四個單詞時,我們保存起始位置並退出循環。現在我們已經開始了第四個單詞,我們可以從該索引獲取子字符串。如果我們沒有得到4個單詞,我們會返回@""

1

最好的答案在這裏:How to get the first N words from a NSString in Objective-C?

你只需要改變的範圍內。

+0

這實際上是倒置的問題。那裏接受的答案也不是區域意識。它僅適用於使用空格分隔單詞的語言。而第二個答案A)採用了更復雜的API,比我們現在可以在'NSString'使用,和b)假定當前區域是字符串的語言環境,而我相信* *'-enumerateSubstrings的默認行爲... '從文本中檢測語言環境。 – 2013-03-12 19:51:13

0

關閉我的頭頂,而不是華而不實的凱文·巴拉德的解決方案:

NSString *phrase = @"I went to the store to buy milk."; 

NSMutableString *words = [[NSMutableString alloc] init]; 
NSArray *words = [phrase componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 

NSMutableIndexSet *indexes = [NSMutableIndexSet indexSetWithIndex:1]; 
[indexes addIndex:2]; 
[indexes addIndex:3]; 
[words removeObjectsAtIndexes:indexes]; 

NSString *output = [words componentsJoinedByString:@" "]; 

我的代碼不會爲不使用的話(如普通話和其他一些遠東語言)之間的空間語言工作。

1

解決方案#1:只是按照您手動操作的方式執行操作:跳過前n個空格。

NSString *cutToNthWord(NSString *orig, NSInteger idx) 
{ 
    NSRange r = NSMakeRange(0, 0); 
    for (NSInteger i = 0; i < idx; i++) { 
     r = [orig rangeOfString:@" " 
         options:kNilOptions 
          range:NSMakeRange(NSMaxRange(r), orig.length - NSMaxRange(r))]; 
    } 
    return [orig substringFromIndex:NSMaxRange(r)]; 
} 

溶液#2(清潔器):分裂在空格字符串,加入所得到的陣列,其中k是詞語要跳過的號碼的最後n - k元件,n是字的總數:

NSString *cutToNthWord(NSString *orig, NSInteger idx) 
{ 
    NSArray *comps = [orig componentsSeparatedByString:@" "]; 
    NSArray *sub = [comps subarrayWithRange:NSMakeRange(idx, comps.count - idx)]; 
    return [sub componentsJoinedByString:@" "]; 
}