如何在 Swift 字符串中找到最后一次出现的子字符串? [英] How do I find the last occurrence of a substring in a Swift string?

查看:46
本文介绍了如何在 Swift 字符串中找到最后一次出现的子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Objective-C 中我使用了:

In Objective-C I used:

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

但现在 NSBackWardsSearch 似乎不存在.谁能提供 Swift 的等效代码?

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

如果可能的话,我希望能够在整个字符串中找到字符数.所以在上面的例子中它会返回 3.

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.

推荐答案

Cocoa 框架应该可以在 Swift 中访问,但您需要导入它们.尝试导入 Foundation 以访问 NSString API.来自使用 Cocoa 数据类型 – 字符串" 的将 Swift 与 Cocoa 和 Objective-C 结合使用"指南:

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 自动桥接 String 类型和 NSString 类.[...] 要启用字符串桥接,只需导入 Foundation.

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

此外,NSBackwardsSearch 是一个枚举值(标记为 & 导入为选项),因此您必须使用 Swift 的 enum/option 语法来访问它(作为 NSStringCompareOptions 选项类型的一部分).前缀从 C 枚举 值,因此删除值名称中的 NS.

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.

综合起来,我们有:

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

请注意,您可能必须使用 distanceadvance 函数以正确使用 rangeOfString 中的范围.

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

这篇关于如何在 Swift 字符串中找到最后一次出现的子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆