0

I have created some strings as below:

let firstname = ""
let lastname = ""    
let myInfo = "Dana<fname>Dana<lname>CEO<occupation>0123456<hp>01234567<wp>dana@gmail.com<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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Mg Dana
  • 67
  • 1
  • 7

2 Answers2

1

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>dana@gmail.com<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"]
Sulthan
  • 128,090
  • 22
  • 218
  • 270
0

You can replace occurrences of string with another string to do it. Example: Any way to replace characters on Swift String?

Community
  • 1
  • 1
Axel
  • 768
  • 6
  • 20
  • I was able to figure it out with componentSeperatedByString. I also have to tweak my string as well. Thank you for your help. – Mg Dana Jan 08 '17 at 20:30