2013-01-15 166 views
0

很奇怪。我预计最后的NSLog打印3,但它不是objectivec - nsrange的计算很奇怪

NSString *value = @"0(234)6"; 

NSRange beginParenthesis = [value rangeOfString:@"("]; 
NSRange endParenthesis = [value rangeOfString:@")"]; 

if (beginParenthesis.location != NSNotFound && endParenthesis.location != NSNotFound) 
{ 
    NSLog(@"%ld", endParenthesis.location); // 5 
    NSLog(@"%ld", beginParenthesis.location + 1); // 2 
    NSLog(@"%ld", endParenthesis.location - beginParenthesis.location + 1); // 5? 
} 

我保存beginParenthesis.location + 1变量...它的工作以及我的预期......为什么?

NSRange beginParenthesis = [value rangeOfString:@"("]; 
NSRange endParenthesis = [value rangeOfString:@")"]; 

if (beginParenthesis.location != NSNotFound && endParenthesis.location != NSNotFound) 
{ 
    NSInteger start = beginParenthesis.location + 1; 
    NSLog(@"%ld", endParenthesis.location); //5 
    NSLog(@"%ld", start); // 2 
    NSLog(@"%ld", endParenthesis.location - start); // 3 
} 

这些论点有什么不同?

回答

2

数学问题:

endParenthesis.location - beginParenthesis.location + 1给出了U(5 - 1 + 1)即等于TO5。 但endParenthesis.location - 开始插上U 5 - 2即3

所以你把这样的括号:

NSLog(@"%ld", endParenthesis.location - (beginParenthesis.location + 1)); 
+0

谢谢。我很尴尬...... – user1705636

+0

嘿,好吧不要,会发生很多次。寒意:) –