Extract Last Word in String with Swift

后端 未结 6 1056
傲寒
傲寒 2020-12-09 12:13

What is the way of extracting last word in a String in Swift? So if I have \"Lorem ipsum dolor sit amet\", return \"amet\". What is the most efficient way of doing this?

6条回答
  •  长情又很酷
    2020-12-09 12:42

    The same solution by '@Leo Dabus' but without slices: (Swift 4.x)

        let fullName = "Williams Diaz Robert"
        let words = fullName.components(separatedBy: " ")
        if(words.count < 2) {
            return
        }
        let fistName = String(words.last ?? "") //Robert
        let lastNameArray = words.prefix(words.count - 1)   //["Williams","Diaz"]: [String]
        let lastName = lastNameArray.joined(separator: " ") // "Williams Diaz"
    

提交回复
热议问题