swift string range of substring

在 Swift 中,你可以使用 range(of:) 方法来查找子字符串在原字符串中的位置。这个方法返回一个 Range 类型的结果,表示子字符串在原字符串中的位置范围。

例如,如果你想要查找子字符串 "cat" 在字符串 "The cat in the hat" 中的位置,你可以这样写:

let string = "The cat in the hat"
if let range = string.range(of: "cat") {
    // range 表示子字符串 "cat" 在原字符串 "The cat in the hat" 中的位置范围
    print(range)  // 输出 "4..<7"

如果你想要获取子字符串在原字符串中的起始位置,你可以使用 range.lowerBound 属性。例如:

let string = "The cat in the hat"
if let range = string.range(of: "cat") {
    let startIndex = range.lowerBound
    print(startIndex)  // 输出 "4"

如果你想要获取子字符串在原字符串中的结束位置,你可以使用 range.upperBound 属性。例如:

let string = "The cat in the hat"
if let range = string.range(of: "cat") {
    let endIndex = range.upperBound
    print(endIndex)  // 输出 "7"

请注意,range(of:) 方法的返回结果是一个可选类型(Range?),因为子字符串有可能不存在于原字符串中。所以在使用这个方法时,你需要对返回结果进行解包,或者使用可选

  •