簡體   English   中英

Ruby:如何計算字符串開頭和結尾的空格數?

[英]Ruby: How to count the number of spaces at the beginning and end of a string?

為了計算字符串s的開頭和結尾的空格數,我這樣做:

s.index(/[^ ]/)              # Number of spaces at the beginning of s
s.reverse.index(/[^ ]/)      # Number of spaces at the end of s

s僅包含要單獨處理的空格時,此方法需要邊緣情況。

有沒有更好(更優雅/更有效)的方法呢?

另一個版本,這必須是最短的

s[/\A */].size
s[/ *\z/].size

您可以一次執行:

_, spaces_at_beginning, spaces_at_end = /^( *).*?( *)$/.match(s).to_a.map(&:length)

絕對不會更優雅。

我不知道它是否更有效,但這也可以。

s.count(' ') - s.lstrip.count(' ')
s.count(' ') - s.rstrip.count(' ')
s.split(s.strip).first.size
s.split(s.strip).last.size

你也可以

beginning_spaces_length , ending_spaces_length = s.split(s.strip).map(&:size) 

這也很容易做到:

beginning =  s.length - s.lstrip.length
ending = s.length - s.rstrip.length

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM