In my iOS app I have team names saved as
very_complex name (number playes)
and to get the full name of the team I would need to read/split that string according to this format
%s (%s)
like we are used to doing with ``sscanf()`in C. How do we do that in Swift?
Unfortunately there's no in-place replacement for sscanf() but the way to do it is to use class Scanner (Apple documentation and by raywenderlich.com).
For your case:
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!))")
Result:
My Team Name (2 players)
My Team Name
2
players
My Team Name (2 players)
** updated to current format, as suggested by Nicholas Allio
**
I'm sure someone will come along with a regex solution - but until then, you can always parse strings with 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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With