S
S
Sir0zha2019-11-15 20:55:17
Swift
Sir0zha, 2019-11-15 20:55:17

How can I repeat an element count times in a function?

Condition:
Write a function called repeatString which repeats the given String src exactly count times.
repeatStr(6, "I") // "IIIIII"
repeatStr(5, "Hello") // "HelloHelloHelloHelloHello"
Initial function:
func repeatStr(_ n: Int, _ string: String) -> String {
// Code here
return ""
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander D., 2019-11-15
@Sir0zha

Three options at a glance (by difficulty level):

func repeatStr0(_ n: Int, _ string: String) -> String {
            var accumulator = ""
            for _ in 0 ..< n {
                accumulator.append(string)
            }
            return accumulator
        }

        func repeatStr1(_ n: Int, _ string: String) -> String {
            var accumulator = ""
            (0 ..< n).forEach {_ in accumulator.append(string) }
            return accumulator
        }

        func repeatStr2(_ n: Int, _ string: String) -> String {
            return (0 ..< n).reduce(into: "") { s, _ in s.append(string) }
        }

1 more, bonus:
repeatElement("asd", count: 5).joined()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question