2013-08-17 21 views
-4

我需要從字符串中得到像這樣的符號(「5,15,7-10」) 和符號,直到第一個逗號需要寫入第一個字符串,直到第二個字符串進入第二個字符串和符號分隔短劃線需要寫入數組,並重新計算第一個到最後一個的值。從NSString解析整數,包括一個範圍

+0

刪除和[重新發布您的問題(http://stackoverflow.com/questions/18294335/parsing-integers-including-a-range-from-nsstring)在這裏不受理。將來,請編輯您的問題。 –

回答

1

您需要使用componentSeparatedByString:

NSString *list = @"5, 15, 7-10"; 
NSArray *listItems = [list componentsSeparatedByString:@", "]; 

這將返回一個數組,看起來像@[@"5", @"15", @"7-10"];

從我明白你的問題,應該工作。儘管你可能想要改進你的問題,但有點難以理解。如果你這樣做,我做了什麼沒有工作id很樂意修復解決方案。

編輯:下面的代碼你想要做什麼(我想):

NSString *list = @"5, 15, 7-10"; 
NSArray *listItems = [list componentsSeparatedByString:@", "]; 
NSMutableArray *expandedList = [[NSMutableArray alloc] init]; 

for(NSString *s in listItems){ 
    NSRange found = [s rangeOfString:@"-"]; 
    if (found.location == 1) { 
     NSArray *hyphenString = [s componentsSeparatedByString:@"-"]; 
     NSInteger first = [[hyphenString objectAtIndex:0] intValue]; 
     NSInteger last = [[hyphenString objectAtIndex:1] intValue]; 
     [expandedList addObject:@(first)]; 
     NSInteger trueDiff = (last - first) - 1; 
     int i = 0; 
     while (i < trueDiff){ 
      first = first + 1; 
      [expandedList addObject:@(first)]; 
      i++; 
     } 
     [expandedList addObject:@(last)]; 

    } else { 
     [expandedList addObject:[NSNumber numberWithInt:[s intValue]]]; 
    } 
} 
NSLog(@"%@", expandedList); 

將輸出:

2013-08-17 21:12:54.579 NumWork[693:303] (
    5, 
    15, 
    7, 
    8, 
    9, 
    10 
) 
+0

非常感謝。 但我需要返回兩個字符串5和15和數組,其中包含值從7到10. –

+0

是否7-10總是會在字符串的末尾? –

+0

不,它可能到處 –