所以如果你有一个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";
如何做到这一点?
答案 0 :(得分:59)
假设有以下输入:
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];
}
答案 1 :(得分:12)
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
}
}
答案 2 :(得分:9)
在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"
答案 3 :(得分:7)
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)
}
答案 4 :(得分:3)
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);
答案 5 :(得分:1)
此处发布了更快速的实现版本。这与Swift 5.1中的语法replacingOccurrences(of:with:)
匹配
extension String {
func replacingFirstOccurrence(of target: String, with replacement: String) -> String {
guard let range = self.range(of: target) else { return self }
return self.replacingCharacters(in: range, with: replacement)
}
}
用法示例:
let string = "I like bacon, please give me some more bacon!"
let newString = string.replacingFirstOccurrence(of: "bacon", with: "meat")
答案 6 :(得分:0)
首先找到子字符串,然后进行替换。示例:
NSString *aString = @"foo bar foo";
NSRange firstFooRange = [aString rangeOfString:@"foo"];
NSString *anotherString = [aString stringByReplacingOccurrencesOfString:@"foo"
withString:@"bar"
options:0
range:firstFooRange];
NSString文档。
答案 7 :(得分:0)
-(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;
}