Donc si vous avez un NSString qui va:
@"My blue car is bigger than my blue shoes or my blue bicycle";
Je voudrais une méthode qui remplace seulement la première instance de blue par green, pour produire:
@"My green car is bigger than my blue shoes or my blue bicycle";
Comment est-que quelqu'un peut faire ça?
En supposant les entrées suivantes:
NSString *myString = @"My blue car is bigger then my blue shoes or my blue bicycle";
NSString *original = @"blue";
NSString *replacement = @"green";
L'algorithme est assez simple:
NSRange rOriginal = [myString rangeOfString:original];
if (NSNotFound != rOriginal.location) {
myString = [myString stringByReplacingCharactersInRange:rOriginal withString:replacement];
}
Mises à jour Swift 3 et 4:
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
}
}
Dans Swift, il est utile d’étendre String de cette manière:
public extension String {
func stringByReplacingFirstOccurrenceOfString(target: String, withString replaceString: String) -> String {
if let range = self.rangeOfString(target) {
return self.stringByReplacingCharactersInRange(range, withString: replaceString)
}
return self
}
}
De cette façon, vous pouvez appeler n'importe où:
let s = "The red red cat".stringByReplacingFirstOccurrenceOfString("red", withString: "fat")
print(s) // "The fat red cat"
Version Swift 4:
func replacingFirstOccurrence(of string: String, with replacement: String) -> String {
guard let range = self.range(of: string) else { return self }
return replacingCharacters(in: range, with: replacement)
}
NSString *initialString = @"My blue car is bigger then my blue shoes or my blue bicycle";
NSRange range = [initialString rangeOfString:@"blue"];
NSString *replacedString = [initialString stringByReplacingCharactersInRange:range withString:@"green"];
NSLog(@"replacedString: %@", replacedString);
-(NSString*) replaceFirstOccuarnceFromString: (NSString*)input withOriginal:(NSString*) original AndReplacment:(NSString*)replacement
{
NSRange rOriginal = [input rangeOfString: original];
if (NSNotFound != rOriginal.location) {
input = [input
stringByReplacingCharactersInRange: rOriginal
withString: replacement];
}
return input;
}
Commencez par localiser la sous-chaîne, puis effectuez le remplacement. Exemple :
NSString *aString = @"foo bar foo";
NSRange firstFooRange = [aString rangeOfString:@"foo"];
NSString *anotherString = [aString stringByReplacingOccurrencesOfString:@"foo"
withString:@"bar"
options:0
range:firstFooRange];
NSString documentation.