ruby – 从字符串中获取前N个字符而不删除整个单词
发布时间:2020-12-17 04:30:08 所属栏目:百科 来源:网络整理
导读:我想知道是否有一种简单的方法可以从字符串中仅获取N个符号而不会切割整个单词. 例如,我有产品和产品描述信息.描述长度是70到500个符号,但我想只显示前70个符号,如下所示: Coca-Cola is the most popular and biggest-selling soft drink in history,as wel
我想知道是否有一种简单的方法可以从字符串中仅获取N个符号而不会切割整个单词.
例如,我有产品和产品描述信息.描述长度是70到500个符号,但我想只显示前70个符号,如下所示:
那么,普通的子串方法会给我: Coca-Cola is the most popular and biggest-selling soft drink in histor 我需要一个方法来获得这个: Coca-Cola is the most popular and biggest-selling soft drink in ... 解决方法s = "Coca-Cola is the most popular and biggest-selling soft drink in history,as well as the best-known brand in the world." s = s.split(" ").each_with_object("") {|x,ob| break ob unless (ob.length + " ".length + x.length <= 70);ob << (" " + x)}.strip #=> "Coca-Cola is the most popular and biggest-selling soft drink in" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |