仅替换NSString中子字符串的第一个实例

问题描述 投票:33回答:7

所以如果你有一个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";

怎么做到这一点?

iphone objective-c xcode nsstring
7个回答
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];
}

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
    } 
}

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"

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)
}

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);

0
投票

首先找到子字符串,然后进行替换。示例:

NSString *aString = @"foo bar foo";
NSRange firstFooRange = [aString rangeOfString:@"foo"];
NSString *anotherString = [aString stringByReplacingOccurrencesOfString:@"foo"
                                                             withString:@"bar"
                                                                options:0
                                                                  range:firstFooRange];

NSString文档。


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;
}
© www.soinside.com 2019 - 2024. All rights reserved.