Extract Last Word in String with Swift

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

    The other answers are fine if you want to include Foundation classes. If you want to use Swift-only classes then you can do it this way:

    One way to do it is to use indices. This is probably the fastest way with long strings:

    Swift 4:

    let str = "Lorem ipsum dolor sit amet"
    let size = str.reversed().firstIndex(of: " ") ?? str.count
    let startWord = str.index(str.endIndex, offsetBy: -size)
    let last = str[startWord...] // -> "amet"
    

    Or you could split the string:

    Swift 4:

    let str = "Lorem ipsum dolor sit amet"
    let split = str.split(separator: " ")
    let last    = String(split.suffix(1).joined(separator: [" "]))
    let lastTwo = String(split.suffix(2).joined(separator: [" "]))
    
    print(last)    // -> "amet"
    print(lastTwo) // -> "sit amet”
    

    Swift 3:

    let str = "Lorem ipsum dolor sit amet"
    let split = str.characters.split(separator: " ")
    let last    = String(split.suffix(1).joined(separator: [" "]))
    let lastTwo = String(split.suffix(2).joined(separator: [" "]))
    
    print(last)    // -> "amet"
    print(lastTwo) // -> "sit amet”
    

    Swift 2:

    let str = "Lorem ipsum dolor sit amet"
    let split = str.characters.split(Character(" "))
    let last    = String(split.suffix(1).joinWithSeparator([" "]))
    let lastTwo = String(split.suffix(2).joinWithSeparator([" "]))
    
    print(last)    // -> "amet"
    print(lastTwo) // -> "sit amet"
    

提交回复
热议问题