gpt4 book ai didi

swift - 在 Swift 中获取子字符串到索引

转载 作者:行者123 更新时间:2023-11-30 10:35:40 25 4
gpt4 key购买 nike

我想获取直到某个索引的子字符串

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)

最佳答案

此扩展程序可能对您有帮助

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)
}
}

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com