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])
static func scan(s : String, fmt : String) -> [String]
{ var result : [String] = []
var ind : Int = 0 // s upto ind has been consumed
let slen : Int = s.count
var i : Int = 0
while i < fmt.count
{ let c : String = Ocl.at(str: fmt, ind: i+1)
if c == "%" && i < fmt.count - 1
{ let d : String = Ocl.at(str: fmt, ind: i+2)
if d == "s"
{ var schars : String = ""
for j in ind...slen
{ let z : String = Ocl.at(str: s, ind: j+1)
if Ocl.iswhitespace(s: z)
{ break }
else
{ schars = schars + z }
}
result.append(schars)
ind = ind + schars.count
i = i + 1
}
else if d == "d"
{ var ichars : String = ""
for j in ind...slen
{ let z : String = Ocl.at(str: s, ind: j+1)
if Ocl.isMatch(str: z, pattern: "[0-9]")
{ ichars = ichars + z }
else
{ break }
}
result.append(ichars)
ind = ind + ichars.count
i = i + 1
}
else if d == "f"
{ var fchars : String = ""
for j in ind...slen
{ let z : String = Ocl.at(str: s, ind: j+1)
if Ocl.isMatch(str: z, pattern: "[0-9.]")
{ fchars = fchars + z }
else
{ break }
}
result.append(fchars)
ind = ind + fchars.count
i = i + 1
}
}
else
{ if Ocl.at(str: s, ind: ind+1) == c
{ ind = ind+1 }
else
{ return result }
}
i = i + 1
}
return result
}
3条答案
按热度按时间i1icjdpr1#
不幸的是,没有sscanf()的替代品,但方法是使用类Scanner(Apple documentation和raywenderlich.com)。
对于您的情况:
结果:
yacmzcpb2#
根据
Nicholas Allio
的建议更新为当前格式我相信会有人沿着regex解决方案--但在此之前,您始终可以使用
componentsSeparatedByString
解析字符串zazmityj3#
以下是sscanf的近似等效函数,这取决于www.example.com上的Swift OCL库github.com/eclipse/agileuml(在libraries*.zip中):
这是这样使用的:打印(扫描(s:“100#20.5/10”,字体:“%d#%f/%d”))