I am new to swift. Is there a simple way to convert the following string to dictionary format.
Example:
input = "Name: Jack\\n Area: Place\\n FavColor: Blue\\n"
Expected Output:
dict = \[Name: Jack, Area: Place, FavColor: Blue\]
and also leading spaces should be trimmed.
The key-value pairs are always in new line.
My idea is split the string based on new line characters first
lines = input.components(separatedBy: CharacterSet.newlines)
then iterate through lines and split each line based on ":" and put them into dict.
Is there any other efficient way to do it?
CodePudding user response:
A possible solution is Regular Expression, it searches for the pattern word - colon - whitespace(s) - word
and captures both words
let input = "Name: Jack\n Area: Place\n FavColor: Blue\n"
let pattern = "(\\b.*\\b):\\s (\\b.*\\b)" // or "(\\w ):\\s (\\w )"
let regex = try! NSRegularExpression(pattern: pattern)
var result = [String:String]()
regex.matches(in: input).forEach { match in
if let keyRange = Range(match.range(at: 1), in: input),
let valueRange = Range(match.range(at: 2), in: input) {
result[String(input[keyRange])] = String(input[valueRange])
}
}
print(result)
CodePudding user response:
My usual approach is to split the string into an array of strings and use the position to determine if the element is a key or value. After that use stride to loop through the array two element at a time to assign the output dictionary where the first element is the key and the second element is the value.
let input = "Name: Jack\n Area: Place\n FavColor: Blue\n"
let charSet = CharacterSet(charactersIn: "\n:")
let tokenized = input.components(separatedBy: charSet).map {
$0.trimmingCharacters(in: .whitespaces)
}
var dict = [String : String]()
for index in stride(from: 0, to: tokenized.count - 1, by: 2) {
dict[tokenized[index]] = tokenized[index 1]
}