agf119105
agf119105

Reputation: 1810

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

In Objective-C I used:

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

But now NSBackWardsSearch seems not to exist. Could anyone provide equivalent code for Swift?

I would like to be able to find the character number in the whole string if possible. So in the example above it would return 3.

Upvotes: 27

Views: 17515

Answers (4)

Craig Stroman
Craig Stroman

Reputation: 192

Swift 5:

"abc def ghi abc def ghi".range(of: "c", options: NSString.CompareOptions.backwards)

Upvotes: -1

Womble
Womble

Reputation: 5290

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"

Upvotes: 41

phantom_2
phantom_2

Reputation: 573

Swift 3.0:

"abc def ghi abc def ghi".range(of: "c", options: String.CompareOptions.backwards, range: nil, locale: nil)

Upvotes: 19

outis
outis

Reputation: 77400

Cocoa frameworks should be accessible in Swift, but you need to import them. Try importing Foundation to access the NSString API. From "Working with Cocoa Data Types–Strings" of the "Using Swift with Cocoa and Objective-C" guide:

Swift automatically bridges between the String type and the NSString class. [...] To enable string bridging, just import Foundation.

Additionally, NSBackwardsSearch is an enum value (marked & imported as an option), so you have to use Swift's enum/option syntax to access it (as part of the NSStringCompareOptions option type). Prefixes are stripped from C enumeration values, so drop the NS from the value name.

Taken all together, we have:

import Foundation
"abc def ghi abc def ghi".rangeOfString("c", options:NSStringCompareOptions.BackwardsSearch)

Note that you might have to use the distance and advance functions to properly make use of the range from rangeOfString.

Upvotes: 23

Related Questions