很奇怪。我预计最后一个NSLog打印3但它不是
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
}
论文之间有什么区别?
答案 0 :(得分:2)
数学问题:
endParenthesis.location - beginParenthesis.location + 1给出u(5 - 1 + 1),即等于5。 但是endParenthesis.location - start给出了5 - 2,即3。
所以你把括号括起来:
NSLog(@"%ld", endParenthesis.location - (beginParenthesis.location + 1));
答案 1 :(得分:1)
它被称为运算符优先级。请参阅here。