Ruby:如何剥离字符串并获得删除的空白



给定一个字符串,我想strip它,但我想有前和后删除空白。例如:

my_strip("   hello world ")   # => ["   ", "hello world", " "]
my_strip("hello worldt ")    # => ["", "hello world", "t "]
my_strip("hello world")       # => ["", "hello world", ""]

如何实现my_strip ?

解决方案

def my_strip(str)
  str.match /A(s*)(.*?)(s*)z/m
  return $1, $2, $3
end

Test Suite (RSpec)

describe 'my_strip' do
  specify { my_strip("   hello world ").should      == ["   ", "hello world", " "]     }
  specify { my_strip("hello worldt ").should       == ["", "hello world", "t "]      }
  specify { my_strip("hello world").should          == ["", "hello world", ""]         }
  specify { my_strip(" hellon worldn n").should  == [" ", "hellon world", "n n"] }
  specify { my_strip(" ... ").should                == [" ", "...", " "]               }
  specify { my_strip(" ").should                    == [" ", "", ""]                   }
end

嗯,这是我想到的一个解决方案:

def my_strip(s)
  s.match(/A(s*)(.*?)(s*)z/)[1..3]
end

但是,我想知道是否有其他(可能更有效的)解决方案。

def my_strip( s )
  a = s.split /b/
  a.unshift( '' ) if a[0][/S/]
  a.push( '' ) if a[-1][/S/]
  [a[0], a[1..-2].join, a[-1]]
end
def my_strip(str)
  sstr = str.strip
  [str.rstrip.sub(sstr, ''), sstr, str.lstrip.sub(sstr, '')]
end

我会使用regexp:

def my_strip(s)
    s =~ /(s*)(.*?)(s*)z/
    *a = $1, $2, $3
end

最新更新