0

它很奇怪。我预计最后一个 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
}

论文之间有什么区别?

4

2 回答 2

2

数学题:

endParenthesis.location - beginParenthesis.location + 1 给出 u ( 5 - 1 + 1) 即等于 5 。但是 endParenthesis.location - start 给你 5 - 2 即 3。

所以你把括号像这样:

 NSLog(@"%ld", endParenthesis.location - (beginParenthesis.location + 1));
于 2013-01-15T09:49:53.237 回答
1

它称为运算符优先级。见这里

于 2013-01-15T09:54:41.860 回答