Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

ios - Extract Last Word in String with Swift

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use String method enumerateSubstringsInRange. First parameter just pass your string Range<Index>, and the option .byWords. Just append each substring to the resulting collection and return it.

Swift 5 or later (for older Swift syntax check edit history)

import Foundation

extension StringProtocol { // for Swift 4 you need to add the constrain `where Index == String.Index` 
    var byWords: [SubSequence] {
        var byWords: [SubSequence] = []
        enumerateSubstrings(in: startIndex..., options: .byWords) { _, range, _, _ in
            byWords.append(self[range])
        }
        return byWords
    }
}

Usage:

let sentence = "Out of this world!!!"
let words = sentence.byWords             // ["Out", "of", "this", "world"]
let firstWord = words.first      // "Out"
let lastWord = words.last         // world"
let first2Words = words.prefix(2) // ["Out", "of"]
let last2Words = words.suffix(2)   // ["this", "world"]

Without import Foundation

Cleaning punctuation characters filtering the letters and spaces of the string

let clean = sentence.filter{ $0.isLetter || $0.isWhitespace }

find the index after the index of the last space in a string

if let lastIndex = clean.lastIndex(of: " "), let index = clean.index(lastIndex, offsetBy: 1, limitedBy: clean.index(before: clean.endIndex)) {
    let lastWord = clean[index...]
    print(lastWord)   // "world"
}

find the index of the first space in a string

if let index = clean.firstIndex(of: " ") {
    let firstWord = clean[...index]
    print(firstWord)  // "Out""
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...