给定一个字符串,我想剥离
它,但我想删除前后的空格。例如:
my_strip(" hello world ") # => [" ", "hello world", " "]
my_strip("hello world\t ") # => ["", "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
测试套件 (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
关于Ruby:如何剥离字符串并获取删除的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7371190/