【问题标题】:getting substring up to index in Swift [duplicate]在 Swift 中获取子字符串到索引 [重复]
【发布时间】:2019-09-25 03:37:40
【问题描述】:

我想得到一个子字符串到某个索引

let index = n % s.count
let remainderOfS = s.substring(from: index)

但它不允许索引,因为它是 Int 而不是 String.Index。所以我试试

let index = n % s.count
let strIndex = s.formIndex(s.startIndex, offsetBy: index)
let remainderOfS = s.substring(from: strIndex)

但现在抱怨:无法使用类型为“(String.Index,offsetBy:Int)”的参数列表调用“formIndex”,需要类型为“(inout Self.Index,offsetBy:Int)”的参数列表,即使这是我在其他人问这个问题的地方找到的解决方案。我错过了什么?

编辑:这也不起作用

let remainderOfS = String(s[..<index])

引用:'subscript(_:)' 已在此处明确标记为不可用 (Swift.String)

【问题讨论】:

  • @Tommy:你在哪里找到了那个解决方案?

标签: swift substring


【解决方案1】:

这个扩展可能会帮助你

extension String {
    func index(from: Int) -> Index {
        return self.index(startIndex, offsetBy: from)
    }

    func substring(from: Int) -> String {
        let fromIndex = index(from: from)
        return substring(from: fromIndex)
    }

    func substring(to: Int) -> String {
        let toIndex = index(from: to)
        return substring(to: toIndex)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-19
    • 2016-04-13
    • 2019-06-03
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    相关资源
    最近更新 更多