swift - 在swift中找到字符串的最后一个索引

标签 swift swift4

<分区>

在swift 4中你可以使用下面的方法来提取一个子串:

let str = "abcdefghci"
let index = str.index(of: "c") ?? str.endIndex
print(str[...index])

这将打印abc

但是我怎样才能找到最后一个 c 的索引,从该位置提取子字符串?

更新
@vadian 请看附件图片:

enter image description here

最佳答案

使用 range(of 可以向后搜索并使用 lowerBound 作为结束索引。

let str = "abcdefghci"
if let range = str.range(of: "c", options: .backwards)  {
    print(str[...range.lowerBound])
}

关于swift - 在swift中找到字符串的最后一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50923863/

相关文章:

ios - VoIP 铃声不起作用

ios - 快速使用collectionview滑动图像

ios - Swift 4 中的 UIImagePickerController 内存泄漏 Xcode 9

ios - Swift Static TableView 添加额外的行

arrays - 在 Swift 中创建包含不同类型的多维数组

ios - 如何在滚动时折叠 UITableView header

swift - 使用 Moya 刷新身份验证 token

ios - 完成处理程序不返回任何内容,即使它看起来像在单步执行时一样

ios - NSLinguisticTagger:根据标记类型过滤掉指定的标记

swift - 通过 Swift 4 中的窥孔优化结合 SIL 指令