Scanner Example
This page was last reviewed on Dec 23, 2023.
Dot Net Perls
Scanner. Suppose you have a string that contains many encoded values in it, like numbers and strings. This could be a from a file that saves user settings.
With Scanner, part of Foundation, we can parse these values in the order they are stored. Optional values are returned. Many helpful methods, like scanUpToString, can be used.
Example. This program creates 2 Scanners and uses them in different ways. It imports Foundation, which is necessary to access the Scanner without a compile-time error.
Step 1 We create a Scanner and pass a string parameter to it. The input string literal includes some encoded values like the number 123456.
Step 2 We call scanUpToString on the Scanner instance. We specify a space, so the string returned includes all values until a space occurs.
Step 3 We call scanInt. This returns an Optional int, so we must test it to ensure it has a value.
Step 4 The scanDecimal call works the same way as scanInt. This will handle the value 12.3, which has a fractional value.
Step 5 Often we will use Scanner within a loop. Here we use Scanner within a while loop, and test it against isAtEnd.
import Foundation // Step 1: create a Scanner with the specified input string. let input = "bird 123456 12.3" let scanner = Scanner(string: input) // Step 2: scan a string from the input string up to a space. let word = scanner.scanUpToString(" ") print(word ?? "None") // Step 3: scan an int after the first scanned word. let intNext = scanner.scanInt() print(intNext ?? "None") // Step 4: scan a decimal afterwards. let decimalNext = scanner.scanDecimal() print(decimalNext ?? "None") // Step 5: create a Scanner and evaluate it in a loop with isAtEnd. let scanner2 = Scanner(string: "123 124 125") var sum = 0; while !scanner2.isAtEnd { // Scan an int, print a message and sum up the int. let intScanned = scanner2.scanInt() ?? 0 print("Summing \(intScanned)") sum += intScanned } print("Sum: \(sum)")
bird 123456 12.3 Summing 123 Summing 124 Summing 125 Sum: 372
Summary. It is possible to parse a string by first splitting it, but a Scanner can eliminate this step. Scanners maintain their position internally, which makes them more usable.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 23, 2023 (new).
© 2007-2024 Sam Allen.