我在 ruby 中显示一定长度的字符串。一行中只能显示该字符串的 80 个字符。例如,如果字符串长度为 82,那么它将以 2 行显示,如果长度为 250,则字符串将以 5 行等显示,我想在空格而不是单词上拆分。
我是新手,不知道怎么解决。
最佳答案
def wrap(str, max_line_len)
str.scan /(?<=\A| ).{1,#{max_line_len}}(?= |\z)/
end
str = "Little Miss Muffet she sat on her tuffet, eating her curds and whey. Along " +
"came a spider who sat down beside her and frightened Miss Muffet away."
1 2 3
123456789012345678901234567890123
puts wrap(str, 31)
Little Miss Muffet she sat on
her tuffet, eating her curds
and whey. Along came a spider
who sat down beside her and
frightened Miss Muffet away.
puts wrap(str, 32)
Little Miss Muffet she sat on
her tuffet, eating her curds and
whey. Along came a spider who
sat down beside her and
frightened Miss Muffet away.
puts wrap(str, 33)
Little Miss Muffet she sat on her
tuffet, eating her curds and
whey. Along came a spider who sat
down beside her and frightened
Miss Muffet away.
参见 String#scan 。正则表达式为“1
和 max_line_len
字符之间的匹配,紧接在字符串的开头或空格之前,紧接着是空格或字符串的结尾”。 (?<=\A| )
是一个正向后视,而 (?= |\z)
是一个正向前视。
关于html - 显示一定长度的字符串而不截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57440279/