gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:39:55 25 4
gpt4 key购买 nike

我有一个像 "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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com