How do I find the last occurrence of a substring in a Swift string?

前端 未结 4 872
夕颜
夕颜 2020-12-07 00:30

In Objective-C I used:

[@\"abc def ghi abc def ghi\" rangeOfString:@\"c\" options:NSBackwardsSearch];

But now NSBackWardsSearch seems not

4条回答
  •  臣服心动
    2020-12-07 01:18

    And if you want to replace the last substring in a string:

    (Swift 3)

    extension String
    {
        func replacingLastOccurrenceOfString(_ searchString: String,
                with replacementString: String,
                caseInsensitive: Bool = true) -> String
        {
            let options: String.CompareOptions
            if caseInsensitive {
                options = [.backwards, .caseInsensitive]
            } else {
                options = [.backwards]
            }
    
            if let range = self.range(of: searchString,
                    options: options,
                    range: nil,
                    locale: nil) {
    
                return self.replacingCharacters(in: range, with: replacementString)
            }
            return self
        }
    }
    

    Usage:

    let alphabet = "abc def ghi abc def ghi"
    let result = alphabet.replacingLastOccurrenceOfString("ghi",
            with: "foo")
    
    print(result)
    
    // "abc def ghi abc def foo"
    

    Or, if you want to remove the last substring completely, and clean it up:

    let result = alphabet.replacingLastOccurrenceOfString("ghi",
                with: "").trimmingCharacters(in: .whitespaces)
    
    print(result)
    
    // "abc def ghi abc def"
    

提交回复
热议问题