Extract Last Word in String with Swift

后端 未结 6 1045
傲寒
傲寒 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:22

    I would also consider using componentsSeparatedByCharactersInSet, and using the whitespace character set:

    let string = "Lorem ipsum dolor sit amet"
    let stringArray = string.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    print(stringArray.last)
    

提交回复
热议问题