Home > Software engineering >  How do I repeat letters of a string to match the length of another string?
How do I repeat letters of a string to match the length of another string?

Time:11-03

I have a string a 'thermostat' of length 10. I have another string "ice" of length 3.

I want to repeat letters of the second string 'ice' and form a new string to match the length of the first string.

so the expected result would look like 'iceiceicei' of length 10, same as the first string.

How can I implement that?

CodePudding user response:

Use cycle to create an infinite list out of your input word, say "ice". Combine that with take and the length of the other string.

λ> take 10 $ cycle "ice"
"iceiceicei"

CodePudding user response:

rep original str = take (length original) (cycle str)

ghci> rep "thermostat" "ice"
"iceiceicei"

CodePudding user response:

Using length as suggested in the other two answers is not ideal, because it fails for an infinite sequence. Suppose you wanted to repeat ice for the length of some string s, but s were defined as repeat 'x'? Of course, you can never "finish" this task, but the infinite string cycle "ice" is still a correct solution, and you can get any finite prefix of it that you want.

You can achieve this by zipping two lists together, rather than basing a computation on length. This is a common technique for anytime you want to do something with two lists pairwise.

*Main> take 30 $ zipWith const (cycle "ice") (repeat 'x')
"iceiceiceiceiceiceiceiceiceice"

Expressed as a function, this would look like

filledWith :: [a] -> [b] -> [b]
holder `filledWith` items = zipWith const (cycle items) holder

*Main> "thermostat" `filledWith` "ice"
"iceiceicei"

I've used infix notation here because I think it helps remember which input determines the length and which the contents, but of course you can define and use it prefix if you prefer.

  • Related