开发者

How to split a string and skip whitespace?

开发者 https://www.devze.com 2022-12-15 23:25 出处:网络
I have a string like \" Thisis a test \". I want to split the string by the space character. I do it like this:

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

精彩评论

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