使用 Ruby,如何替换字符串中的一系列字符?例如,给定字符串
hellothere
如果我想将索引位置 2 到 5 处的字符替换为“#”以生成字符串
he####here
我该怎么做?
您可以获取字符串范围并通过设置最后一个索引乘以的新字符加上 1 减去第一个索引来替换它:
def replace_in_string(str, replace, start, finish)
str[start..finish] = replace * (finish + 1 - start)
str
end
p replace_in_string 'hellothere', '#', 2, 5
# "he####here"
s = '你好' s[2..5] = '####'