开发者

How to split a string and skip whitespace?

I have a string like " This is a test ". I want to split the string by the space character. I do it like this:

puts " This   is a test ".strip.each(' ') {|s| puts s.strip}

The result is:

This

is

a

test

This is a test

Why is there the last line "This is a test"? And I need, that if there are two or more space characters between two words, that this should not return a "row".

I only want to get the words splitted in a given string.

Does anyone have an i开发者_如何学Pythondea?


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.


You should do

" This   is a test ".strip.each(' ') {|s| puts s.strip}

If you don't want the last "this is a test"

Because

irb>>> puts " This   is a test ".strip.each(' ') {}
This   is a test


The first command "puts" will be put after the each-block is excecuted. omit the first "puts" and you are done

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜