简体   繁体   English

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

[英]Ruby: How to strip a string and get the removed whitespaces?

Given a string, I would like to strip it, but I want to have the pre and post removed whitespaces. 给定一个字符串,我想strip它,但我希望删除前后空格。 For example: 例如:

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

How would you implement my_strip ? 你将如何实现my_strip

Solution

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

Test Suite (RSpec) 测试套件(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

Well, this is a solution that I come up with: 嗯,这是我提出的解决方案:

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

But, I wonder if there are other (maybe more efficient) solutions. 但是,我想知道是否还有其他(可能更有效)的解决方案。

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

I would use regexp: 我会用regexp:

def my_strip(s)
    s =~ /(\s*)(.*?)(\s*)\z/
    *a = $1, $2, $3
end
def my_strip(str)
  sstr = str.strip
  [str.rstrip.sub(sstr, ''), sstr, str.lstrip.sub(sstr, '')]
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM