Swift:相当于sscanf()?

时间:2016-02-23 09:56:50

标签: ios string swift

在我的iOS应用中,我将团队名称保存为

very_complex name (number playes)

并获取团队的全名,我需要根据此格式读取/拆分该字符串

%s (%s)

像我们习惯在C中使用``sscanf()`一样。我们如何在Swift中做到这一点?

2 个答案:

答案 0 :(得分:2)

**按照Nicholas Allio **

的建议更新为当前格式

我确信有人会使用正则表达式解决方案 - 但在此之前,您始终可以使用componentsSeparatedByString解析字符串

let str = "very_complex name (42 players)"
var splitString1 = str.components(separatedBy: " (")
var splitString2 = splitString1[1].components(separatedBy: " ")

let teamName = splitString2[0]
let numberOfPlayers = Int(splitString2[0])

答案 1 :(得分:2)

不幸的是,没有sscanf()的就地替换,但是这样做的方法是使用类扫描器(Apple documentationraywenderlich.com)。

对于你的情况:

let str = "My Team Name (2 players)" // %s (%d %s)
let scanner = Scanner(string: str)
var firstStrVal: NSString?
var dummyStrVal: NSString?
var intVal: Int = 0
var secondStrVal: NSString?

scanner.scanUpTo(" (", into: &firstStrVal)
scanner.scanCharacters(from: CharacterSet.init(charactersIn: "("), into: &dummyStrVal)
scanner.scanInt(&intVal)
scanner.scanUpTo(")", into: &secondStrVal)

print(str)
print(firstStrVal!)
print(intVal)
print(secondStrVal!)
print("\(firstStrVal!) (\(intVal) \(secondStrVal!))")

结果:

My Team Name (2 players)
My Team Name
2
players
My Team Name (2 players)