1

我知道这是一个简单的问题,但由于某种原因它不会点击。我想以固定数量重复字符串中的字符。例如:

str = 'abcde'
temp = ''
x = 8
for i in 0..x
    if str[i].nil?
        temp << ''
    else
        temp << str[i]
    end
end

除了我没有得到任何输入。我需要的是:

abcdeabc

请,任何帮助将不胜感激。如果有更好的工作方式来代替我不工作的幼稚方法,我想知道

4

5 回答 5

4

Using ljust should do it:

str = 'abcde'

str.ljust(8, str)
# => "abcdeabc" 

str.ljust(12, str)
# => "abcdeabcdeab" 
于 2013-02-21T01:06:50.217 回答
3

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
于 2013-02-21T01:01:51.580 回答
1

您可以使用切片轻松地做到这一点

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
于 2013-02-21T00:59:58.137 回答
0

Try this one-liner:

res = (str * (x / str.length)) + str[0...(x%str.length)]
于 2013-02-21T01:04:02.510 回答
0

模拟 str_repeat

"abcde" * 3   
#-> "abcdeabcdeabcde"
于 2019-10-18T07:24:17.887 回答