Im Batman Im Batman - 6 months ago 43
Swift Question

Extract a name from a sentence

I need to get persons name from a sentence.

Example :

My Name is David Bonds and i live in new york.
and I want to extract name
David Bonds

My Name is
is definitely will be in every sentence. but after the name it can contains rest of the sentence or may be nothing. from this answer I was able to get to the point of
My Name is
. but it will print out rest of all the sentence. i want to make sure it will grab only
next two words

if let range = conversation.range(of: "My Name is") {
let name = conversation.substring(from: range.upperBound).trimmingCharacters(in: .whitespacesAndNewlines)

Answer Source

When you have rest of the text you can separate it by " ". Then first and secont elements are first and last name

let array = text.components(separatedBy: " ")

//first name

//last name
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download