简体   繁体   中英

How do I repeat letters of a string to match the length of another string?

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?

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"
rep original str = take (length original) (cycle str)

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

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 zip ping 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM