0

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.

3
  • 1
    look over this: learnswiftonline.com/reference-guides/…. It may be helpful... Commented Jan 8, 2017 at 20:22
  • OMG! im so stupid! Thank you so much for link. Commented Jan 8, 2017 at 20:29
  • You're welcome! If you have any other questions related to string trimming feel free to ask! Commented Jan 8, 2017 at 20:31

2 Answers 2

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>[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"]
Sign up to request clarification or add additional context in comments.

1 Comment

this work like a charm. Also, exactly the way i wanted.
0

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

1 Comment

I was able to figure it out with componentSeperatedByString. I also have to tweak my string as well. Thank you for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.