Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 235
Eric Brotto Avatar asked Dec 22 '11 18:12

Eric Brotto


People also ask

How do you replace a character in a string in Objective C?

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.

What is the difference between string and Nsstring?

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.


2 Answers

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]; } 
like image 115
Jonathan Grynspan Avatar answered Sep 22 '22 21:09

Jonathan Grynspan


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     }  } 
like image 41
Kevin Sabbe Avatar answered Sep 22 '22 21:09

Kevin Sabbe