在我的iOS应用中,我将团队名称保存为
very_complex name (number playes)
并获取团队的全名,我需要根据此格式读取/拆分该字符串
%s (%s)
答案 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 documentation和raywenderlich.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)