简体   繁体   English

如何在 Swift 字符串中找到最后一次出现的子字符串?

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

In Objective-C I used:在 Objective-C 中,我使用了:

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

But now NSBackWardsSearch seems not to exist.但是现在 NSBackWardsSearch 似乎不存在了。 Could anyone provide equivalent code for Swift?谁能为 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.所以在上面的例子中,它会返回 3。

And if you want to replace the last substring in a string:如果要替换字符串中的最后一个子字符串:

(Swift 3) (斯威夫特 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"

Cocoa frameworks should be accessible in Swift, but you need to import them. Cocoa 框架应该可以在 Swift 中访问,但您需要导入它们。 Try importing Foundation to access the NSString API.尝试导入Foundation以访问 NSString API。 From " Working with Cocoa Data Types–Strings " of the "Using Swift with Cocoa and Objective-C" guide:来自“在 Cocoa 和 Objective-C 中使用 Swift”指南的“使用Cocoa 数据类型——字符串”:

Swift automatically bridges between the String type and the NSString class. Swift 会自动桥接 String 类型和 NSString 类。 [...] To enable string bridging, just import Foundation. [...] 要启用字符串桥接,只需导入 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).此外, NSBackwardsSearch是一个枚举值(标记并作为选项导入),因此您必须使用 Swift 的枚举/选项语法来访问它(作为NSStringCompareOptions选项类型的一部分)。 Prefixes are stripped from C enumeration values, so drop the NS from the value name.C 枚举值中去除前缀​​,因此从值名称中删除NS

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 .请注意,您可能需要使用distanceadvance功能正常使用的范围rangeOfString

斯威夫特 3.0:

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

斯威夫特 5:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在NSString中找到最后一个子字符串? - How do I find the last occurrence of a substring in an NSString? 如何找到给定字符串中最后一次出现的子字符串? - How to find last occurrence of a substring in a given string? 如何在字符串中最后一次出现字符后获取子字符串:Swift IOS - How to get substring after last occurrence of character in string: Swift IOS 查找字符串中子字符串最后一次出现的索引 - Find index of last occurrence of a substring in a string 如何在RapidMiner CE计算中找到子字符串的最后一次出现? - How do I locate last occurrence of a substring in a RapidMiner CE calculation? Swift 获取字符串中最后一次出现字符后的 substring - Swift Get substring after last occurrence of character in string 如何在字符串中找到模式最后一次出现的位置,并使用这些位置从另一个字符串中提取子字符串 - How to find positions of the last occurrence of a pattern in a string, and use these to extract a substring from another string 如何在字符串中找到特定的子字符串 - How do I find specific substring in a string 如何提取MySQL中倒数第二个出现的字符串? - How do I extract the second to last occurrence of a string in MySQL? 查找字符串中第 n 次出现的 substring - Find the nth occurrence of substring in a string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM