我希望在分割我的一个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__"
循环遍历此数组根据数组中包含的数值对字符串进行分段的最佳方法是什么?
答案 0 :(得分: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,请创建一个char指针,这比第一种方法稍快。
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);
答案 1 :(得分: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))
})
需要进行额外的验证检查,但这是基本想法。