加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 如何拆分字符串并跳过空格?

发布时间:2020-12-16 20:01:52 所属栏目:百科 来源:网络整理
导读:我有一个字符串,如“这是一个测试”.我想用空格字符分割字符串.我这样做: puts " This is a test ".strip.each(' ') {|s| puts s.strip} 结果是: This is a test This is a test 为什么最后一行“这是一个测试”? 而我需要的是,如果两个字之间有两个或更
我有一个字符串,如“这是一个测试”.我想用空格字符分割字符串.我这样做:
puts " This   is a test ".strip.each(' ') {|s| puts s.strip}

结果是:

This

is
a
test
This is a test

为什么最后一行“这是一个测试”?
而我需要的是,如果两个字之间有两个或更多的空格字符,那就不应该返回一个“行”.

我只想得到一个给定的字符串分割的单词.
有没有人有想法?

解决方法

irb(main):002:0> " This   is a test ".split
=> ["This","is","a","test"]

irb(main):016:0* puts " This   is a test ".split
This
is
a
test

str.split(pattern=$;,[limit]) => anArray

If pattern is omitted,the value of $; is used. If $; is nil (which is the default),str is split on whitespace as if ` ’ were specified.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读