如何通过拆分字符的最后一次出现将字符串拆分为仅两部分? [英] How to split a string into only two parts, by the last occurrence of the split char?

查看:30
本文介绍了如何通过拆分字符的最后一次出现将字符串拆分为仅两部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

"Angry Birds 2.4.1".split(" ", 2)
 => ["Angry", "Birds 2.4.1"] 

如何将字符串拆分为:["Angry Birds", "2.4.1"]

推荐答案

String#rpartition,例如

irb(main):068:0> str = "Angry Birds 2.4.1"
=> "Angry Birds 2.4.1"
irb(main):069:0> str.rpartition(' ')
=> ["Angry Birds", " ", "2.4.1"]

由于返回值是一个数组,使用 .first.last 将允许将结果视为一分为二,例如

Since the returned value is an array, using .first and .last would allow to treat the result as if it was split in two, e.g

irb(main):073:0> str.rpartition(' ').first
=> "Angry Birds"
irb(main):074:0> str.rpartition(' ').last
=> "2.4.1"

这篇关于如何通过拆分字符的最后一次出现将字符串拆分为仅两部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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