gpt4 book ai didi

swift - 如何使用 Range Swift 3 打印字符串

转载 作者:行者123 更新时间:2023-11-28 12:25:02 25 4
gpt4 key购买 nike

我是 Swift 编程的新手。我有一个关于 Swift String 的问题。我有一个显示来自 JSON 的数据的 TableView。片段下方:

cell.labelFOStat.text = ("F/O Status   : \(subString(string: featureStr!, startIndex: 0, endIndex: 11))")

cell.labelHKStat.text = ("H/K Status : \(subString(string: featureStr!, startIndex: 12, endIndex: 23))" )

cell.labelID.text = ("ID : \(subString(string: featureStr!, startIndex: 24, endIndex: 25))")

cell.labelTime.text = ("Time : \(subString(string: featureStr!, startIndex: 26, endIndex: 30))")

cell.labelExplanation.text = ("Explanation : \(subString(string: featureStr!, startIndex: 31, endIndex: 62))")

cell.labelFOAdult.text = ("F/O Adult : \(subString(string: featureStr!, startIndex: 63, endIndex: 64))")

cell.labelFOChild.text = ("F/O Child : \(subString(string: featureStr!, startIndex: 65, endIndex: 66))")

cell.labelHKAdult.text = ("H/K Adult : \(subString(string: featureStr!, startIndex: 67, endIndex: 68))")

cell.labelHKChild.text = ("H/K Child : \(subString(string: featureStr!, startIndex: 69, endIndex: (featureStr?.characters.count)! - 1))")

substring 是:

func subString(string:String, startIndex: Int, endIndex: Int) -> String {
let index = string.index((string.startIndex), offsetBy: startIndex)
let endIndex = string.index((string.startIndex), offsetBy: endIndex)

let t:String?

let str = string[index...endIndex]

return str
}

这是我的 JSON 片段:

[{
"zinr": "1006",
"features": "Occupied Sleep Out 0115:15asd 0 0 0 0",
"etage": 10,
"bezeich": "Deluxe King",
"house-status": 1,
"zistatus": 4,
"userinit": "01",
"nr": 1
}, {
"zinr": "709",
"features": "Vacant Occupied 0112:46tes 0 0 0 0",
"etage": 7,
"bezeich": "Superior King",
"house-status": 1,
"zistatus": 0,
"userinit": "01",
"nr": 1
}]

想知道如何使用字符串 range 获取键 "features"。可以只制作没有开始或结束索引的 range 参数吗? .我读过 this但它仍然让我有点困惑。提前致谢。

最佳答案

最方便(虽然不是最有效)的方法是对 String 进行扩展:

extension String {
subscript(range: CountableRange<Int>) -> String {
let startIndex = self.index(self.startIndex, offsetBy: range.lowerBound)
let endIndex = self.index(self.startIndex, offsetBy: range.upperBound)
return self[startIndex..<endIndex]
}

subscript(range: CountableClosedRange<Int>) -> String {
let startIndex = self.index(self.startIndex, offsetBy: range.lowerBound)
let endIndex = self.index(self.startIndex, offsetBy: range.upperBound)
return self[startIndex...endIndex]
}
}

// Both print Hello
let str = "Hello world"
print(str[0..<5])
print(str[0...4])

关于swift - 如何使用 Range Swift 3 打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43670672/

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