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

1 Answer

0 votes
import Foundation

func moveNthWordToEndOfString(_ input: String, _ n: Int) throws -> String {
    let trimmed = input.trimmingCharacters(in: .whitespacesAndNewlines)
    if trimmed.isEmpty { return trimmed }

    var parts = trimmed.components(separatedBy: .whitespaces).filter { !$0.isEmpty }

    guard n >= 0 && n < parts.count else {
        throw NSError(domain: "IndexOutOfRange", code: 1, userInfo: nil)
    }

    let word = parts.remove(at: n)
    parts.append(word)

    return parts.joined(separator: " ")
}

do {
    let s = "Would you like to know more? (Explore and learn)"
    let n = 2

    let result = try moveNthWordToEndOfString(s, n)
    print(result)
} catch {
    print("Error:", error)
}



/*
run:

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

*/

 



answered Feb 6 by avibootz
...