gpt4 book ai didi

ruby - 从 Ruby 字符串中按索引删除字符

转载 作者:数据小太阳 更新时间:2023-10-29 07:24:08 25 4
gpt4 key购买 nike

给定一个包含字符串索引的序列,

str_indices = [[1,2],[7,8]],

从字符串中排除这些的最佳方法是什么?

例如,给定上述标记为排除的索引和字符串 happydays,我希望返回 hpyda

最佳答案

使用范围:

str_indices=[[1,2],[7,8]]
str="happydays"
str_indices.reverse.each{|a| str[Range.new(*a)]=''}
str
=> "hpyda"

如果不想修改原件:

str_indices.reverse.inject(str){|s,a|(c=s.dup)[Range.new(*a)]='';c}

关于ruby - 从 Ruby 字符串中按索引删除字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5734930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com