Home > Software design >  Mexican wave in Swift string
Mexican wave in Swift string

Time:11-17

I need to print a String as if a Mexican Wave is passing through each character in the String:

wave("hello") -> ["Hello", "hEllo", "heLlo", "helLo", "hellO"]

For current moment I'm stopped at:

var str = "hel lo"
var arr = [String]()
str = str.lowercased()
str = str.replacingOccurrences(of: " ", with: "")

for i in str {
    arr.append (str.replacingOccurrences(of: "\(i)", with: i.uppercased()))
}
print(arr)

CodePudding user response:

You can simply map your string indices and replace its character at each iteration:


let string = "hello"
let result = string.indices.map {
    string.replacingCharacters(in: $0...$0, with: string[$0...$0].uppercased()) 
}

print(result)

This will print:

["Hello", "hEllo", "heLlo", "helLo", "hellO"]

CodePudding user response:

Here is a solution where I use prefix and suffix together with a character from an uppercased version of the string in a for loop then enumerates the uppercased string

func wave(_ string: String) -> [String] {
    if string.isEmpty { return [] }
    var result = [String]()
    
    for (index, char) in string.uppercased()() {
        result.append("\(string.prefix(index))\(char)\(string.suffix(string.count - index - 1))")
    }    
    return result
}

In case the in string contains punctuation, digits or any other value that can't be uppercased then it's no point in adding that case to the result array so here is an alternative for that:

func wave(_ string: String) -> [String] {
    if string.isEmpty { return [] }
    var result = [String]()

    for (index, char) in string.uppercased().enumerated() {
        guard char.isLetter else { continue }
        result.append("\(string.prefix(index))\(char)\(string.suffix(string.count - index - 1))")
    }
    return result
}
  • Related