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 は u 5 - 2 つまり 3 を与えます。

したがって、次のように括弧を付けます。

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

その呼ばれる演算子の優先順位。ここを参照してください。

于 2013-01-15T09:54:41.860 に答える