需要为给定长度的给定字符串辩护,
ss = "There is an example to make Justify the text us"
Total length = 50
必需的输出:
ss = "There is an example to make Justify the text us"
此处字符串的长度调整为50个字符,在第一个字符“那里”之后添加间距,最后一个字符“我们”,“文本”。
尝试过,
qw = ""
string.split(" ").each_with_index do |x,i|
qw = qw + " " + x
end
但无法添加空间
答案 0 :(得分:1)
试试这个,
str = 'There is an example to make Justify the text us'
words = str.split
width, remainder = (50 - words.map(&:length).inject(:+)).divmod(words.length - 1)
width, remainder = 1, 0 if width.zero? # take care of long lines
words.take(words.length - 1).each { |word| width.times { word << 32 }}
words.take(words.length - 1).shuffle.take(remainder).each { |word| word << 32 }
p words.join
这是如何运作的?
k
k
字答案 1 :(得分:0)
您的示例代码无效的原因是split
使用了分隔符。
'a b c'.split.to_a #=> ['a', 'b', 'c']
当您手动重新组合字符串时,您需要在消耗分隔空间的位置添加单个空格(),从而产生相同的字符串。
根据评论的建议,您还没有向我们提供有关您希望如何处理此问题的足够信息。如果只有一个单词,会发生什么?如果我们有比行更多的字符怎么办?你想如何减重空间?你需要考虑文本的渲染宽度吗?这很快就变成了一个更复杂的项目。
但请注意,大多数视图 - 无论是移动设备,网络设备还是外壳设备 - 都有方法可以证明您可以使用的文本效果很好。
所有人都说,这是一个忽略边缘情况的工作实例:
input = "There is an example to make Justify the text us"
words = input.split
spaces_needed = 50 - input.scan(/[^ ]/).length
spaces_per_word = Float(spaces_needed) / (words.count - 1)
words.each_with_index.map do |word, i|
word += ' ' if (spaces_per_word * (i + 1)) % 1 == 0
word
end.join(' ')
答案 2 :(得分:0)
假设你想先在最后一个单词中添加空格,然后再到第一个单词,再到倒数第二个单词等等:
def justify(str, length)
words = str.split(/\s+/)
cnt = words.size - 1
return str if cnt < 1
return str if str.size >= length
diff = length - str.size
base = diff / cnt + 1
rest = diff % cnt
cnt.times.each.with_index do |word, i|
r = [i + 1, cnt - i - 1].min * 2 <= rest && rest > 0 ? 1 : 0
rest -= r
words[i] << " " * (base + r)
end
words.join
end
justify("There is an example to make Justify the text us", 50)
#=> "There is an example to make Justify the text us"
justify("One more example", 50)
#=> "One more example"
justify("Or this", 50)
#=> "Or this"
justify("Example", 50)
#=> "Example"
justify("There is an example to make Justify the very long text us", 50)
#=> "There is an example to make Justify the very long text us"
答案 3 :(得分:0)
这是一种相当可读的方法:
def padString (str,width)
words = str.split.map{|s|s+" "} # words single spaced
padding = width-words.join.length+1 # how much needs adding?
locations = words.size - 1 # places space can be added
return str if padding<0 or words==[] # abort if string too long or empty
padding.times {
words[rand(locations)] += " " # append space to random location
}
words.join.strip! # reconstitute the string
end
它会随机添加填充,因此每次都会得到不同的行:
padString("There is an example to make Justify the text us",50)
=> "There is an example to make Justify the text us"
padString("There is an example to make Justify the text us",50)
=> "There is an example to make Justify the text us"
padString("hey you",50)
=> "hey you"
padString("hey",50)
=> "hey"