ios - swift 4.0 中的子字符串从索引 0 到所需的索引

标签 ios swift swift4

我有一个字符串:

"08 sept 2017 10:56 AM"

我想把这个字符串分成两个字符串:dateStrtimeStr

我为 dateStr 试过这个:

let createdDateStr = transactionModel.created_on! //"08 sept 2017 10:56 AM"
let dateCount = createdDateStr.characters.count - 8
let timeStr = createdDateStr.substring(dateCount)

它有效,但我不知道如何为 dateStr 做同样的事情。

我有一个字符串扩展:

func substring(_ from: Int) -> String {
    let start = index(startIndex, offsetBy: from)
    return String(self[start ..< endIndex])
}

最佳答案

您应该为此使用部分范围。试试这个扩展:

func substring(to: Int) -> String {
    let end = index(startIndex, offsetBy: to)
    return String(self[..< end])
}

let dateCount = createdDateStr.characters.count - 8
let dateStr = createdDateStr.substring(to: dateCount)

关于ios - swift 4.0 中的子字符串从索引 0 到所需的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46216813/

相关文章:

ios - Recursion::How to create a mini-view of 3d scenekit of self on top of self?

ios - IBDesignable UIView 子类总是无法在 Interface Builder 中呈现

json - 如何在 Swift 4 中正确解析带有根元素的 JSON 作为数组?

ios - Swift 4 - iOS 11 搜索栏范围不会出现,因为它应该

swift - 执行终端命令时无法访问文件

objective-c - 如何在iPad上显示MS Office 2007/2010文件的内容?

ios - 如果日期更改则执行操作

ios - 如何在 Swift 中创建一个使用 "self"的全局变量

ios - <TextInput keyboardType ="numeric"/> 在 native react 中不起作用

ios - 隐藏/显示 UINavigationBar 会导致 UICollectionView 更改其框架