Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: which the equivalent of sscanf()?

Tags:

string

ios

swift

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?

like image 475
SagittariusA Avatar asked Feb 23 '16 09:02

SagittariusA


2 Answers

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)
like image 177
Dark Avatar answered Oct 22 '22 14:10

Dark


** 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])
like image 3
Russell Avatar answered Oct 22 '22 13:10

Russell