所以如果你有一个NSString:
@"My blue car is bigger than my blue shoes or my blue bicycle";
我想要一个方法,只用蓝色替换第一个蓝色实例,以产生:
@"My green car is bigger than my blue shoes or my blue bicycle";
怎么做到这一点?
假设以下输入:
NSString *myString = @"My blue car is bigger then my blue shoes or my blue bicycle";
NSString *original = @"blue";
NSString *replacement = @"green";
算法很简单:
NSRange rOriginal = [myString rangeOfString:original];
if (NSNotFound != rOriginal.location) {
myString = [myString stringByReplacingCharactersInRange:rOriginal withString:replacement];
}
SWIFT 3和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
}
}
在Swift中,以这种方式扩展String非常有用:
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
}
}
通过这种方式你可以在任何地方打电话:
let s = "The red red cat".stringByReplacingFirstOccurrenceOfString("red", withString: "fat")
print(s) // "The fat red cat"
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 *aString = @"foo bar foo";
NSRange firstFooRange = [aString rangeOfString:@"foo"];
NSString *anotherString = [aString stringByReplacingOccurrencesOfString:@"foo"
withString:@"bar"
options:0
range:firstFooRange];
NSString文档。
-(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;
}