我有一个像 "This is a test "
这样的字符串。我想用空格字符拆分字符串。我这样做:
puts " This is a test ".strip.each(' ') {|s| puts s.strip}
结果是:
This
is
a
test
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.
关于ruby - 如何拆分字符串并跳过空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2005148/