gpt4 book ai didi

swift - 在 Swift5 中获取部分字符串

转载 作者:行者123 更新时间:2023-11-30 10:41:49 24 4
gpt4 key购买 nike

我正在尝试从 Swift5 中的给定输入字符串中提取部分字符串。就像字符串中的字母 2 到 5 一样。

我确信,像 inputString[2...5] 这样简单的事情会工作,但我只能像这样工作:

String(input[(input.index(input.startIndex, offsetBy: 2))..<(input.index(input.endIndex, offsetBy: -3))])

...仍然使用相对位置(endIndex-3 而不是 位置 #5)

现在我想知道我到底哪里搞砸了。

人们通常如何通过绝对位置从“abcdefgh”中提取“cde”?

最佳答案

我为速记子字符串编写了以下扩展,而无需在主代码中处理索引和转换:

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

let testString = "HelloWorld!"

print(testString.substring(from: 0, to: 4)) // 0 to 4 inclusive

输出Hello

关于swift - 在 Swift5 中获取部分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56614440/

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