簡體   English   中英

Ruby:如何剝離字符串並獲取刪除的空格?

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

給定一個字符串,我想strip它,但我希望刪除前后空格。 例如:

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

嗯,這是我提出的解決方案:

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

我會用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