给定一个字符串,我想strip
它,但我希望删除前后空格。例如:
my_strip(" hello world ") # => [" ", "hello world", " "]
my_strip("hello world\t ") # => ["", "hello world", "\t "]
my_strip("hello world") # => ["", "hello world", ""]
您将如何实施my_strip
?
答案 0 :(得分:3)
<强>解决方案强>
def my_strip(str)
str.match /\A(\s*)(.*?)(\s*)\z/m
return $1, $2, $3
end
测试套件(RSpec)
describe 'my_strip' do
specify { my_strip(" hello world ").should == [" ", "hello world", " "] }
specify { my_strip("hello world\t ").should == ["", "hello world", "\t "] }
specify { my_strip("hello world").should == ["", "hello world", ""] }
specify { my_strip(" hello\n world\n \n").should == [" ", "hello\n world", "\n \n"] }
specify { my_strip(" ... ").should == [" ", "...", " "] }
specify { my_strip(" ").should == [" ", "", ""] }
end
答案 1 :(得分:2)
嗯,这是我提出的解决方案:
def my_strip(s)
s.match(/\A(\s*)(.*?)(\s*)\z/)[1..3]
end
但是,我想知道是否还有其他(可能更有效)的解决方案。
答案 2 :(得分:1)
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
答案 3 :(得分:1)
我会用regexp:
def my_strip(s)
s =~ /(\s*)(.*?)(\s*)\z/
*a = $1, $2, $3
end
答案 4 :(得分:1)
def my_strip(str)
sstr = str.strip
[str.rstrip.sub(sstr, ''), sstr, str.lstrip.sub(sstr, '')]
end