Split String into Array by Words
Splitting a string into an array based on the word sounds daunting initially, however is quite simple. To achieve this follow the sample code below:
let sentence = "Hello im Seemu" let wordsArray = sentence.components(separatedBy: " ") let wordFirst = wordsArray[0] // Hello let wordSecond = wordsArray[1] // im let wordThird = wordsArray[2] // Seemu print(wordFirst) print(wordSecond) print(wordThird)
This will result in the output as follows:
Hello im Seemu
One use of this sort of splitting is getting a first name and last name separately as follows:
let name: String = "Bob Smith" let wordsName = name.components(separatedBy: " ") let firstName = wordsName[0] let lastName = wordsName[1] print(firstName) // Bob print(lastName) // Smith
This will give you the following output:
Bob Smith
Just note, be careful if someone has a middle name, example “Bob Joey Smith” as you will get unexpected results!