How do I remove repeated spaces in a string?

前端 未结 7 1743
悲哀的现实
悲哀的现实 2020-12-29 20:05

I have a string:

\"foo (2 spaces) bar (3 spaces) baaar (6 spaces) fooo\"

How do I remove repetitious spaces in it so there shou

7条回答
  •  一整个雨季
    2020-12-29 20:31

    Which method performs better?

    $ ruby -v
    ruby 1.9.2p0 (2010-08-18 revision 29036) [i686-linux]
    
    $ cat squeeze.rb 
    require 'benchmark'
    include Benchmark
    
    string = "foo  bar   bar      baaar"
    n = 1_000_000
    bm(6) do |x|
      x.report("gsub      ") { n.times { string.gsub(/\s+/, " ") } }
      x.report("squeeze   ") { n.times { string.squeeze } }
      x.report("split/join") { n.times { string.split.join(" ") } }
    end
    
    $ ruby squeeze.rb 
                user     system      total        real
    gsub        4.970000   0.020000   4.990000 (  5.624229)
    squeeze     0.600000   0.000000   0.600000 (  0.677733)
    split/join  2.950000   0.020000   2.970000 (  3.243022)
    

提交回复
热议问题