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

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

iphone - Replace only the first instance of a substring in an NSString

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

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

1 Answer

0 votes
by (71.8m points)

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];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...