问题
I know this is a simple problem, but for some reason it wont click. I want to repeat characters in a string for a fixed amount. For example:
str = 'abcde'
temp = ''
x = 8
for i in 0..x
if str[i].nil?
temp << ''
else
temp << str[i]
end
end
Except I get no input. What I need is:
abcdeabc
Please, any help would be appreciated. If there is a better working way to do this instead of my not working naive approach, I would like to know
回答1:
Using ljust
should do it:
str = 'abcde'
str.ljust(8, str)
# => "abcdeabc"
str.ljust(12, str)
# => "abcdeabcdeab"
回答2:
If you want to repeat a string a few times, use *
. We can combine that with slicing to get this solution:
def repfill(str, n)
nrep = (Float(n) / str.length).ceil
return (str * nrep)[0...n]
end
Example:
irb(main):030:0> repfill('abcde', 8)
=> "abcdeabc"
As for your solution, what you are missing is a modulo to repeat the string from the beginning:
str = 'abcde'
temp = ''
x = 8
for i in 0...x # note ... to exclude last element of range
temp << str[i % str.length]
end
回答3:
You can easily do this using slicing
def repeat_x_chars(str, x)
# special cases
return str if x == 0
return "" if str.length == 0
return str + str[0..(str.length % x)] # slicing
end
回答4:
Try this one-liner:
res = (str * (x / str.length)) + str[0...(x%str.length)]
回答5:
analog str_repeat
"abcde" * 3
#-> "abcdeabcdeabcde"
来源:https://stackoverflow.com/questions/14992775/repeat-characters-in-a-string