我知道这是一个简单的问题,但由于某种原因它不会点击。我想以固定数量重复字符串中的字符。例如:
str = 'abcde'
temp = ''
x = 8
for i in 0..x
if str[i].nil?
temp << ''
else
temp << str[i]
end
end
除了我没有得到任何输入。我需要的是:
abcdeabc
请,任何帮助将不胜感激。如果有更好的工作方式来代替我不工作的幼稚方法,我想知道
Using ljust
should do it:
str = 'abcde'
str.ljust(8, str)
# => "abcdeabc"
str.ljust(12, str)
# => "abcdeabcdeab"
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
您可以使用切片轻松地做到这一点
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
Try this one-liner:
res = (str * (x / str.length)) + str[0...(x%str.length)]
模拟 str_repeat
"abcde" * 3
#-> "abcdeabcdeabcde"