Search code examples
swiftnsscanner

Swift scanUpToString not working as expected


Iam having issues with scanUpToString method and its not working as I expect

let str1 = "123-456-7890"
let scanner = Scanner(string: str1)
let part1  = scanner.scanUpToString("-")
let part2  = scanner.scanUpToString("-")
let part3 = scanner.scanUpToString("-")

I am getting 123 for part1, but nil for part2 and part3

Is there anything more that I need to do get part2 = 456 and part3 = 7890 ?


Solution

  • The issue there is that the scanner is finding the same string "-" at the current index over and over again. If you need to use this method you would need to move the currentIndex one character forward after each scan:

    let str1 = "123-456-7890"
    let scanner = Scanner(string: str1)
    let part1  = scanner.scanUpToString("-")  // "123"
    scanner.currentIndex = str1.index(after: scanner.currentIndex)
    let part2  = scanner.scanUpToString("-")  // "456"
    scanner.currentIndex = str1.index(after: scanner.currentIndex)
    let part3 = scanner.scanUpToString("-")  // "7890"