这是一个难题: 我有一个字符串列表,每个字符串格式:
\w+==============================\w+
==============================
两侧的字数可能不同。用更多=
填充每个字符串以便所有字符串具有相同长度的好方法是什么?在单词之间应该至少有30个=
个字符。
即,我有这个清单:
[ "Hello World==============================Bye!",
"This==============================Should",
"Be==============================Padded nicely!"]
变成:
[ "Hello World===============================Bye!",
"This====================================Should",
"Be==============================Padded nicely!"]
答案 0 :(得分:4)
a = [ "Hello World===============================Bye!",
"This====================================Should",
"Be==============================Padded nicely!"]
max = a.map(&:length).max
a.map{|l| l.sub(/(?:==)/, "=" * (max - l.length))}
答案 1 :(得分:0)
您希望使用 more =
个字符填充每个字符串,以便所有字符串的长度相同,每个字符串至少包含30个=
个字符。我想提供一个解决方案,允许某些字符串的=
个数减少,只要它们都填充到相同的长度,每个字符串至少有30 {=
1}}字符和至少一个字符串恰好有30 =
个(认识到这可能不适合你)。这为填充的字符串长度产生了一个minimax解决方案,受两个约束条件的限制。
<强>代码强>
def pad(a, min_equals)
b = a.map { |s| s.split(/=+/) }.map { |e| [e.join.size] + e }
longest = b.transpose.first.max
b.map { |(len,head,tail)| head + '='*(min_equals+longest-len) + tail }
end
示例强>
a = [ "Hello World==============================Bye!",
"This==============================Should",
"Be==============================Padded nicely!"]
pad(a,30)
#=> ["Hello World===============================Bye!",
# "This====================================Should",
# "Be==============================Padded nicely!"]
<强>解释强>
c = a.map { |s| s.split(/=+/) }
#=> [["Hello World", "Bye!"], ["This", "Should"], ["Be", "Padded nicely!"]]
b = c.map { |e| [e.join.size] + e }
#=> [[15, "Hello World", "Bye!"], [10, "This", "Should"],
# [16, "Be", "Padded nicely!"]]
d = b.transpose
#=> [[15, 10, 16], ["Hello World", "This", "Be"],
# ["Bye!", "Should", "Padded nicely!"]]
e = d.first
#=> [15, 10, 16]
longest = e.max
#=> 16
b.map { |(len,head,tail)| head + '='*(30+longest-len) + tail }
#=> ["Hello World===============================Bye!",
# "This====================================Should",
# "Be==============================Padded nicely!"]