如果我在变量中有文字说
Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old
如何将最后一行放在下一行?
Lorem Ipsum is not simply random text.
It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old
答案 0 :(得分:0)
如果要显示要在下一行显示的段落的最后一行,可以使用\n
。
喜欢
"Lorem Ipsum is not simply random text. \nIt has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old"
答案 1 :(得分:0)
使用rpartition
分隔最后一句。
string = "Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old"
start, middle, finish = string.rpartition('. ')
answer = middle == '. ' ? [start, finish].join(".\n") : finish
puts answer
=> Lorem Ipsum is not simply random text.
It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old
三元组的原因是处理没有找到句子的情况("。"),在这种情况下整个字符串将在finish
变量中。
答案 2 :(得分:0)
如果您希望它可以使用任意数量的段落,只需为最后一段创建一个新行,您可以使用:
to_fix_1 = "Somewhere above. The cityscape. Gerwefegrrfqegrwb.".split('.')
to_fix_2 = "Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old".split('.')
converter = lambda { |splitted, res| splitted.each_with_index { |p,i| (i+1) == splitted.length && splitted.length != 1 ? (res += "\n"+p.strip+'.') : (res += p+'.') } and return res }
result = converter.call(to_fix_1, '')
puts result
=> Somewhere above. The cityscape.
Gerwefegrrfqegrwb.
result = converter.call(to_fix_2, '')
puts result
=> Lorem Ipsum is not simply random text.
It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.
(我只是很开心写作,不要判断)