2014-10-11 72 views
0

我希望得到一些幫助來拆分我的一個NSString值。考慮以下以下:基於數值的NSString拆分字符串

NSString *string = @"_o_t_d_n__"; 

基本上,我想段此NSString *string以上到3個獨立的字符串值的基礎上,數字定界符下面它們被存儲在一個NSArray:

NSArray *values = [NSArray arrayWithObjects: @3, @2, @5]; 

哪個會那麼造成以下,基於這些分隔符值:

3 = @"_o_" 
2 = @"t_" 
6 = @"d_n__" 

什麼會通過這個數組分割循環最好的方法基於數組中包含的數值的字符串?

回答

3

試試這個:

NSArray *array = @[@(3),@(2),@(5)]; 
NSUInteger loc = 0; 
for (int i = 0; i < [array count]; i++) { 
    NSUInteger len = [[array objectAtIndex:i] unsignedIntegerValue]; 
    NSString *subStr = [string substringWithRange:NSMakeRange(loc, len)]; 
    loc += len; 
} 

如果你想通過的NSString環路,做一個字符指針,這比第一種方法稍快。

NSString *string = @"_o_t_d_n__"; 
const char *c = [string cStringUsingEncoding:NSUTF8StringEncoding]; 
char *myData = calloc(3, 1); 
for (int i = 0, j = 0; i < [string length]; i++, j++) { 
    myData[j] = c[i]; 
    if (i == 2 || i == 4 || i == 9) { 
     NSString *string = [[NSString alloc] initWithBytes:myData length:sizeof(myData) encoding:NSUTF8StringEncoding]; 
     NSLog(@"%@",string); 
     if (i == 2) myData = realloc(myData, 2); 
     if (i == 4) myData = realloc(myData, 5); 
     j = -1; 
    } 
} 
free(myData); 
+0

謝謝。當然會讓我更清楚。我可以通過循環以某種方式做到這一點嗎? – Maff 2014-10-11 05:57:25

+0

現貨伴侶。非常感激! – Maff 2014-10-11 08:17:39

0

我會使用正則表達式來做到這一點。下面是我該怎麼做:

let string = "_o_t_d_n__" 
let first = 3 
let second = 2 
let third = 5 
let expression = NSRegularExpression.regularExpressionWithPattern("([a-z]{\(first)})([a-z]{\(second)})([a-z]{\(third),})", options: nil, error: nil) 
let range = NSMakeRange(0, string.length) 
expression.enumerateMatchesInString(string, options: nil, range: range, usingBlock:{ (result, MatchingFlags, unsafePointer) in 
     let firstResult = string.substringWithRange(result.rangeAtIndex(1)) 
     let secondResult = string.substringWithRange(result.rangeAtIndex(2)) 
     let thirdResult = string.substringWithRange(result.rangeAtIndex(3)) 
}) 

需要額外的驗證檢查,但這是基本的想法。

+0

順便說一下,這是SWIFT代碼。 Objective-c是一樣的。 – 2014-10-11 05:40:26