Say*_*yuj 58 ruby string replace
a = "foobarfoobarhmm"
我希望输出为"fooBARfoobarhmm"
即只有第一次出现的"bar"应该用"BAR"代替.
Yos*_*ssi 115
用途#sub:
a.sub('bar', "BAR")
Run Code Online (Sandbox Code Playgroud)
tbu*_*ann 16
String#sub就像Yossi已经说过的那样,你就是你所需要的.但我会使用Regexp,因为它更快:
a = 'foobarfoobarhmm'
output = a.sub(/foo/, 'BAR')
Run Code Online (Sandbox Code Playgroud)
要替换第一个匹配项,只需执行以下操作:
str = "Hello World"
str['Hello'] = 'Goodbye'
# the result is 'Goodbye World'
Run Code Online (Sandbox Code Playgroud)
你甚至可以使用正则表达式:
str = "I have 20 dollars"
str[/\d+/] = 500.to_s
# will give 'I have 500 dollars'
Run Code Online (Sandbox Code Playgroud)