仅替换NSString中子字符串的第一个实例
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了仅替换NSString中子字符串的第一个实例相关的知识,希望对你有一定的参考价值。
所以如果你有一个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;
}
以上是关于仅替换NSString中子字符串的第一个实例的主要内容,如果未能解决你的问题,请参考以下文章