我正在尝试将除法运算符/
添加到String
,它取整数。
运算符应生成一个字符串数组。数组的大小是给定的整数,其元素是原始的子串,当按顺序连接时,产生原始字符串。
如果字符串长度不能被整数整除,则某些子字符串应该(一个字符)比其他字符串长。没有两个字符串的长度不应超过一个,任何更长的字符串应该出现在任何较短的字符串之前。
像这样:
"This is a relatively long string" / 7
# => ["This ", "is a ", "relat", "ively", " lon", "g st", "ring"]
我该如何开始?
答案 0 :(得分:2)
class String
def /(num)
n, rem = self.size.divmod(num)
p = 0
res = []
rem.times{res << self[p..p+n]; p+=n+1}
(num-rem).times{res << self[p...p+n]; p+=n}
res
end
end
p "This is a relatively long string" / 7
["This ", "is a ", "relat", "ively", " lon", "g st", "ring"]
答案 1 :(得分:2)
你可以使用递归。
class String
def /(n)
return [self] if n==1
m = (self.size.to_f/n).ceil
[self[0...m]].concat(self[m..-1] / (n-1))
end
end
str = "This would be a woefully short string had I not padded it out."
str / 7
# => ["This woul", "d be a wo", "efully sh", "ort strin", "g had I n",
# "ot padded", " it out."]
(str / 7).map(&:size)
#=> [10, 10, 9, 9, 9, 9, 9]
答案 2 :(得分:2)
这样可行:
class String
def /(n)
chars.in_groups(n).map(&:join)
end
end
"This is a relatively long string" / 7
#=> ["This ", "is a ", "relat", "ively", " lon", "g st", "ring"]
even as per MDN transparent
maps only to rgba(0,0,0,0)
是一个Rails方法,用于在 n 组中拆分数组。
答案 3 :(得分:0)
这是我的解决方案,有点笨重但O(n)时间。
如果有任何边缘情况,请告知我们:
class String
def /(num)
if num > self.length
return [] # or whatever, since this is an edge case / can't be done
end
remainder = self.length % num
result = []
substr = ""
i = 1
while i <= self.length
substr += self[i-1]
if i % (self.length / num) == 0
if remainder > 0
substr += self[i]
i += 1
remainder -= 1
end
result << substr
substr = ""
end
i += 1
end
result
end
end
编辑:重构 - 用子字符串替换子数组
答案 4 :(得分:-2)
class String
def /(num)
partition_size = length / num
if length % num == 0
scan /.{#{partition_size}}/
else
scan /.{#{partition_size},#{partition_size + 1}}/
end
end
end