Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

So if you have an NSString that goes:

@"My blue car is bigger than my blue shoes or my blue bicycle";

I would like a method that replaces only the first instance of blue with green, to produce:

@"My green car is bigger than my blue shoes or my blue bicycle";

How does one do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
302 views
Welcome To Ask or Share your Answers For Others

1 Answer

Assuming the following inputs:

NSString *myString = @"My blue car is bigger then my blue shoes or my blue bicycle";
NSString *original = @"blue";
NSString *replacement = @"green";

The algorithm is quite simple:

NSRange rOriginal = [myString rangeOfString:original];

if (NSNotFound != rOriginal.location) {
    myString = [myString stringByReplacingCharactersInRange:rOriginal withString:replacement];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...