How to move a word to the end of a string in Swift

1 Answer

0 votes
import Foundation  

func moveWordToEnd(_ s: String, word: String) -> String {
    // Split on whitespace
    var parts = s.split { $0.isWhitespace }.map(String.init)

    // Find and remove the first occurrence
    if let index = parts.firstIndex(of: word) {
        parts.remove(at: index)
        parts.append(word)
    }

    // Rebuild the string
    return parts.joined(separator: " ")
}

let s = "Would you like to know more? (Explore and learn)"
let word = "like"

let result = moveWordToEnd(s, word: word)
print(result)




/*
run:

Would you to know more? (Explore and learn) like

*/

 



answered Feb 5 by avibootz
...