Im Batman Im Batman - 1 month ago 9
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
only.

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

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
print(array[0])

//last name
print(array[1])