Reputation: 233
It is strange. I expected that the last NSLog print 3 but it wasn't
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?
}
And I saved beginParenthesis.location + 1 to variable...it worked well I expected...why?
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
}
What differece between theses?
Upvotes: 0
Views: 205
Reputation: 3274
Maths Problem:
endParenthesis.location - beginParenthesis.location + 1 gives u ( 5 - 1 + 1) i.e equal to5 . But endParenthesis.location - start gives u 5 - 2 i.e 3.
So you put the parenthesis like this:
NSLog(@"%ld", endParenthesis.location - (beginParenthesis.location + 1));
Upvotes: 2