Вопрос

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.

Это было полезно?

Решение

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)

Другие советы

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"];
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top