Question

I have an NSMutableString that holds the string "I have ∞ Hours and ∞ Min to spare." and I am trying to replace the first ∞ with a "0" by doing

NSMutableString *timeString = [NSMutableString stringWithString:@"And I have ∞ Hours and ∞ Min to spare."];
NSLog(@"%@",timeString);
[timeString replaceCharactersInRange:NSMakeRange(11,12) withString:@"0"];
NSLog(@"%@",timeString);

However, instead of only replacing the first ∞, it replaces the phrase "∞ Hours and "

Here is what is printed out in console:

And I have ∞ Hours and ∞ Min to spare.
And I have 0∞ Min to spare.

I don't understand why its deleting characters beyond the specified range.

Était-ce utile?

La solution

A range is made up of (location, length)

You are saying start at 11 and span 12 characters from there. You;re effectively making a range of 11 to 22.

You need:

NSMakeRange(11,1)

Autres conseils

The second parameter of a range is the length, not the ending position, so you should pass 1 there if you're trying to replace 1 character.

The second value in NSMakeRange is length of the range, not position of the end.

Try with

NSMakeRange(11,1)

Do it like this ..!

NSMutableString *timeString = [NSMutableString stringWithString:@"And I have ∞ Hours and ∞ Min to spare."];

NSRange range = [timeString rangeOfString:@"∞"];
if (range.location != NSNotFound)
{
[timeString replaceCharactersInRange:range withString:@"0"];
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top