显示一定长度的字符串而不会被截断 [英] Show a string of certain length without truncating
问题描述
我正在显示一定长度的红宝石字符串.该字符串中只能显示80个字符.例如,如果字符串长度为82,那么如果长度为250,它将显示为2行;如果字符串为250,则字符串将显示为5行,以此类推,我想在空格上拆分而不是单词.
I am displaying a string of certain length in ruby. only 80 characters of that string can be displayed in one line. for example if string length is 82 then it will be shown in 2 lines if length is 250 then string will be shown in 5 lines etc and i want to split on whitespace not the word.
我是新来的,所以不知道该怎么解决.
I am new in this so don't know how can i solve this.
推荐答案
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)
是正向后看.
See String#scan. The regular expression reads, "match between 1
and max_line_len
characters, immediately preceded by the beginning of the string or a space and immediately followed by a space or the end of the string". (?<=\A| )
is a positive lookbehind and (?= |\z)
is a positive lookahead.
这篇关于显示一定长度的字符串而不会被截断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!