xcode22
xcode22

Reputation: 128

How to split one long string of words into separate words in Swift?

Im working on this problem that has a string of words with no spaces. I have to achieve is to add a space to this input between the words. Here is the code I have:

func getOrder(_ input: String) -> String {

let menu = ["Pizza", "Milkshake", "Fries", "Onionrings", "Burger", "Coke", "Sandwich", "Chicken"]

    
return ""
}

getOrder("milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza")

Upvotes: 0

Views: 142

Answers (1)

Joakim Danielson
Joakim Danielson

Reputation: 52108

Here is one way to do it, loop over the menu array and replace each found occurrence of a menu item with the item and a space

func getOrder(_ input: String) -> String {
    
    let menu = ["Pizza", "Milkshake", "Fries", "Onionrings", "Burger", "Coke", "Sandwich", "Chicken"]
    
    var result = input
    menu.forEach { word in
        result = result.replacingOccurrences(of: word.lowercased(), with: "\(word) ")
    }
    
    return result.trimmingCharacters(in: .whitespaces)
}

Upvotes: 2

Related Questions