我有一句話說:沒有在一句影響換句話說空格打破擠壓話
The fox j u m p e d over the big b r o w n boar !
我想更換成這樣:
The fox jumped over the big brown boar !
(注 - 擠壓空間當在中間,但留下完整的單詞和感嘆號)
我寫了這樣的代碼這樣做:
str = 'The fox j u m p e d over the big b r o w n boar !'
prev_char = '0'
prev_prev_char = '0'
next_next_char = '0'
new_str = ''
(0..(str.length)).each do |index|
t_char = str[index]
prev_char = index > 0 ? str[index-1] : '0'
prev_prev_char = index > 1 ? str[index-2] : '0'
next_next_char = index-1 < str.length ? str[index+2] : '0'
new_str = "#{new_str}#{t_char}" unless t_char == ' ' && prev_char != ' ' && prev_prev_char == ' ' && next_next_char == ' '
end
results = new_str.split(' ').join(' ')
p (results == 'The fox jumped over the big brown boar !')
但我確定有一個更好或更聰明的方法。有什麼建議麼?
從「狐狸」中我們可以預計什麼? – Toto
@ M42我會指望它是'狐狸跳起來......' –
那麼聚合字母的規則是什麼?爲什麼'狐狸'變成'狐狸'而不是'狐狸'? – Toto