[" ", "hello world", " "] my_strip-6ren">
gpt4 book ai didi

Ruby:如何剥离字符串并获取删除的空格?

转载 作者:数据小太阳 更新时间:2023-10-29 08:21:18 25 4
gpt4 key购买 nike

给定一个字符串,我想剥离它,但我想删除前后的空格。例如:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com