如何使用Range或任何其他方法从Swift中的字符串中提取子字符串?

时间:2016-10-04 19:54:44

标签: string swift2

我有这个程序,我试图提取两个字符串之间的数字,但是当我使用substringWithRange函数

时,我得到编译时错误(如下所示)

编译时错误:

/Users/chandeln/Documents/ApplePaySwag-Starter/ApplePaySwag/BuySwagViewController.swift:382:47: Cannot convert value of type 'Range<Int>' to expected argument type 'Range<Index>' (aka 'Range<String.CharacterView.Index>')

代码:

let text = "[DeviceAccountNumber-Start]4817499130007700[DeviceAccountNumber-End]"

//get the position of the start string 
let danStartTagRange: Range<String.Index> = text.rangeOfString("[DeviceAccountNumber-Start]")!
let danStartTagIndex: Int = text.startIndex.distanceTo(danStartTagRange.startIndex)
let danStartTagEndingIndex: Int = text.startIndex.distanceTo(danStartTagRange.endIndex)
print("danStartTagRange = \(danStartTagRange)")
print("danStartTagIndex = \(danStartTagIndex)")
print("danStartTagEndingIndex = \(danStartTagEndingIndex)")

//get the position of the end string 
let danEndTagRange: Range<String.Index> = text.rangeOfString("[DeviceAccountNumber-End]")!
let danEndTagIndex: Int = text.startIndex.distanceTo(danEndTagRange.startIndex)
let danEndTagEndingIndex: Int = text.startIndex.distanceTo(danEndTagRange.endIndex)
print("danEndTagRange = \(danEndTagRange)")
print("danEndTagIndex = \(danEndTagIndex)")
print("danEndTagEndingIndex = \(danEndTagEndingIndex)")
let rangeOfDan = danStartTagEndingIndex..<danEndTagIndex

//get the actual dan now based on the above derived variables
let dan = text.substringWithRange(rangeOfDan)
let dan =  substringFromIndex(danStartTagEndingIndex);
print("dan = \(dan)")

之前运行的输出:

danStartTagRange = 0..<27
danStartTagIndex = 0
danStartTagEndingIndex = 27
danEndTagRange = 43..<68
danEndTagIndex = 43
danEndTagEndingIndex = 68

我正在使用Swift 2.3

请指导。

1 个答案:

答案 0 :(得分:2)

试试这样:

Xcode 8•Swift 2.3

let text = "[DeviceAccountNumber-Start]4817499130007700[DeviceAccountNumber-End]"

if let startIndex = text.rangeOfString("[DeviceAccountNumber-Start]")?.endIndex,
    let endIndex = text.rangeOfString("[DeviceAccountNumber-End]")?.startIndex {
    let dan = text.substringWithRange(startIndex..<endIndex)
    print("dan = \(dan)")   // "dan = 4817499130007700\n"
}

Xcode 8•Swift 3

let text = "[DeviceAccountNumber-Start]4817499130007700[DeviceAccountNumber-End]"

if let lowerBound = text.range(of: "[DeviceAccountNumber-Start]")?.upperBound,
    let upperBound = text.range(of: "[DeviceAccountNumber-End]")?.lowerBound {
    let dan = text.substring(with: lowerBound..<upperBound)
    print("dan = \(dan)")   // "dan = 4817499130007700\n"
}