Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string and skip whitespace?

Tags:

string

split

ruby

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 idea?

like image 706
Tim Avatar asked Jan 05 '10 09:01

Tim


People also ask

Does string split remove whitespace?

Split method, which is not to trim white-space characters and to include empty substrings.

How do you split a string by whitespace?

You can split a String by whitespaces or tabs in Java by using the split() method of java. lang. String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces.

How do I split a string without a separator?

To split a string without removing the delimiter: Use the str. split() method to split the string into a list.

How do you split a string by space and punctuation?

To split a string by space or comma, pass the following regular expression to the split() method - /[, ]+/ . The method will split the string on each occurrence of a space or comma and return an array containing the substrings.


2 Answers

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.

like image 92
YOU Avatar answered Oct 21 '22 08:10

YOU


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
like image 26
marcgg Avatar answered Oct 21 '22 08:10

marcgg