Eri*_*ric 1 ruby string substring
标题可能令人困惑.只是说我有一篇报纸文章.我想在某个点附近剪掉它,比如4096个字符,但不是在一个单词的中间,而是在最后一个长度超过4096的单词之前.这是一个简短的例子:
"This is the entire article."
Run Code Online (Sandbox Code Playgroud)
如果我想在一个总长度超过16个字符的单词之前剪掉它,这就是我想要的结果:
"This is the entire article.".function
=> "This is the"
Run Code Online (Sandbox Code Playgroud)
单词"whole"的总长度超过16,因此必须删除它,以及它之后的所有字符以及它之前的空格.
这是我不想要的:
"This is the entire article."[0,15]
=> "This is the ent"
Run Code Online (Sandbox Code Playgroud)
写作看起来很容易,但我不知道如何将其用于编程.
对于你的例子,这样的事情怎么样:
sentence = "This is the entire article."
length_limit = 16
last_space = sentence.rindex(' ', length_limit) # => 11
shortened_sentence = sentence[0...last_space] # => "This is the"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1819 次 |
| 最近记录: |