将字符串截断为前 n 个单词 [英] Truncate string to the first n words

查看:28
本文介绍了将字符串截断为前 n 个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将字符串截断为前 n 个单词的最佳方法是什么?

What's the best way to truncate a string to the first n words?

推荐答案

n = 3
str = "your long    long   input string or whatever"
str.split[0...n].join(' ')
 => "your long long"


str.split[0...n] # note that there are three dots, which excludes n
 => ["your", "long", "long"]

这篇关于将字符串截断为前 n 个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆