0

I need to read some formatted data from a string and store it in two variables. The string has this format:

data = "(1234),(-567)"

The numbers are of varying lengths and signs. I feel like this should be simple. It would be easy in C:

scanf(data, "(%d),(%d)", num1, num2)

But in Swift, I'm pulling my hair out trying to find an easy way to do this. As suggested in other answers, I've tried:

data.components(separatedBy: CharacterSet.decimalDigits.inverted)

However this overlooks minus signs. Any help is much appreciated!

4

2 回答 2

0

我喜欢正则表达式:

let data = "(1234),(-567)"
let pattern = "\\((.*?)\\)"
let reg = try! NSRegularExpression(pattern: pattern)
let result = reg.matches(in: data, options: [], 
    range: NSMakeRange(0, data.utf16.count))
let numstrings = result.map {(data as NSString).substring(with: $0.rangeAt(1))}
let nums = numstrings.map {Int($0)!} // I'm feeling lucky
// [1234, -567]
于 2017-11-12T02:09:27.350 回答
0

您可以Scanner在需要scanf类似行为时使用:

let data = "(1234),(-567)"

var num1: CInt = 0
var num2: CInt = 0
let scanner = Scanner(string: data)
if
    scanner.scanString("(", into: nil),
    scanner.scanInt32(&num1),
    scanner.scanString("),(", into: nil),
    scanner.scanInt32(&num2),
    scanner.scanString(")", into: nil)
{
    print(num1, num2)
} else {
    print("failed")
}
于 2017-11-12T01:51:21.293 回答