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?
To replace a character in objective C we will have to use the inbuilt function of Objective C string library, which replaces occurrence of a string with some other string that we want to replace it with.
Essentially, there is no difference between string and String (capital S) in C#. String (capital S) is a class in the . NET framework in the System namespace. The fully qualified name is System.
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]; }
SWIFT 3 and 4 UPDATE:
extension String { func stringByReplacingFirstOccurrenceOfString( target: String, withString replaceString: String) -> String { if let range = self.range(of: target) { return self.replacingCharacters(in: range, with: replaceString) } return self } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With