在Swift 3.0中使用String.range

1286
2023/9/8 8:58:39
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Swift 3.0中,你可以使用String.range来获取子字符串在原始字符串中的位置。这里是一个简单的示例:

let str = "Hello, World!"
let range = str.range(of: "World")
if let range = range {
let startIndex = str.distance(from: str.startIndex, to: range.lowerBound)
let endIndex = str.distance(from: str.startIndex, to: range.upperBound)
print("Found at index \(startIndex) to \(endIndex)")
} else {
print("Not found")
}

输出结果将是 “Found at index 7 to 12”,表示子字符串 “World” 在原始字符串中的位置范围。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: Swift的语法特点有哪些