Reputation: 77
I have created some strings as below:
let firstname = ""
let lastname = ""
let myInfo = "Dana<fname>Dana<lname>CEO<occupation>0123456<hp>01234567<wp>[email protected]<email>"
I want to extract certain parts out of that string. For example, I want to assign the part before <fname>
to the firstname
variable, and the part before <lname>
to the lastname
variable.
Upvotes: 0
Views: 128
Reputation: 130072
Just a fast idea, probably there is some simpler way to do that:
let myInfo = "Dana<fname>Dana<lname>CEO<occupation>0123456<hp>01234567<wp>[email protected]<email>"
let components = myInfo.components(separatedBy: CharacterSet(charactersIn: "<>"))
let values = components.enumerated().filter { $0.offset % 2 == 0 }.map { $0.element }
let keys = components.enumerated().filter { $0.offset % 2 == 1 }.map { $0.element }
var namedValues: [String: String] = [:]
for i in keys.indices {
namedValues[keys[i]] = values[i]
}
print(namedValues)
Then just:
let firstName = namedValues["fname"]
let lastName = namedValues["lname"]
Upvotes: 1
Reputation: 778
You can replace occurrences of string with another string to do it. Example: Any way to replace characters on Swift String?
Upvotes: 0