【问题标题】:How to split a string and skip whitespace?如何拆分字符串并跳过空格?
【发布时间】:2010-01-05 09:45:05
【问题描述】:

我有一个类似" This is a test " 的字符串。我想用空格字符分割字符串。我是这样做的:

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

结果是:

这个


一个
测试
这是一个测试

为什么最后一行有"This is a test"? 而且我需要,如果两个单词之间有两个或更多空格字符,则不应返回“行”。

我只想将单词拆分为给定的字符串。
有人有想法吗?

【问题讨论】:

    标签: ruby string split


    【解决方案1】:
    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

    如果省略pattern,则$的值; 用来。如果 $;是零(这是 默认),str在空格上分割 好像指定了 ` '。

    【讨论】:

      【解决方案2】:

      你应该这样做

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

      如果你不想要最后一个“这是一个测试”

      因为

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

      【讨论】:

        【解决方案3】:

        第一个命令“puts”将在每个块被执行后put。 省略第一个“puts”就完成了

        【讨论】:

          猜你喜欢
          • 2020-12-01
          • 2014-02-11
          • 2017-10-20
          • 1970-01-01
          • 2019-07-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多