从字符串中删除重复子
答
您正在寻找sub!
:
str = "hi ram hi shyam hi jhon"
str.sub!("hi ", "")
#=> "ram hi shyam hi jhon"
str.sub!("hi ", "")
#=> "ram shyam hi jhon"
str.sub!("hi ", "")
#=> "ram shyam jhon"
套内你做什么修改原始的字符串,这不是这个例子的样子,你可能想使用sub
来代替,并且一个额外的变量
答
str = "hi ram hi shyam hi jhon"
要删除一个发生:
str.sub('hi', '').strip.squeeze
#⇒ "ram hi shyam hi jhon"
要删除n个出现:
n.times { str.replace(str.sub('hi', '').strip.squeeze) }
答
我假设你要删除的所有单词重复出现,而不是仅仅"hi"
。这有两种方法。
1使用String#reverse,Array#reverse和Array#uniq
str = "hi shyam ram hi shyam hi jhon"
str.split.reverse.uniq.reverse.join(' ')
#=> "ram shyam hi jhon"
为uniq
状态的文档: “self
遍历有序,并第一次出现,保持为”
2使用正则表达式
r =/
\b # match a word break
(\w+) # match a word in capture group 1
\s # match a trailing space
(?= # begin a positive lookahead
.* # match any number of characters
\s # match a space
\1 # match the contents of capture group 1
\b # match a word break
) # end the positive lookahead
/x # free-spacing regex definition mode
str.gsub(r, '')
#=> "ram shyam hi jhon"
要删除多余的空格的正则表达式定义的第三行改变\s
到\s+
。
这家伙在开玩笑说我脱掉了我的药! Upvoted :) – mudasobwa