Ruby:已知无需reverse方法反转字符串,如何仅反转奇数索引字符?
如何仅反转字符串中的奇数索引字符?
已知可以通过以下Ruby代码在不使用reverse方法的情况下实现整串反转:
def reverse(string) string.each_char.inject(""){|str, char| str.insert(0, char) } end puts reverse('hello world') # 输出: dlrow olleh
现在需要实现仅反转字符串中的奇数索引字符(索引从0开始计数),以输入'hello world'为例,期望输出为hlloo wlred。
实现思路
核心思路是分离出原字符串中奇数索引的字符,反转这部分字符后,再将它们按顺序放回原字符串的奇数索引位置:
- 提取原字符串所有奇数索引的字符,组成数组并反转;
- 遍历原字符串的每个字符,遇到奇数索引时,用反转后的奇数字符数组依次替换;
- 最后将处理后的字符数组拼接成字符串。
代码实现
def reverse_odd_indices(string) chars = string.chars # 提取奇数索引的字符并反转 reversed_odd_chars = chars.select.with_index { |_, idx| idx.odd? }.reverse # 替换原数组中的奇数索引字符 chars.each_with_index do |_, idx| chars[idx] = reversed_odd_chars.shift if idx.odd? end chars.join end # 测试 puts reverse_odd_indices('hello world') # 输出: hlloo wlred
代码说明
chars.select.with_index { |_, idx| idx.odd? }:筛选出原字符串中所有奇数索引的字符;reversed_odd_chars.shift:每次从反转后的奇数字符数组头部取出一个元素,保证替换顺序正确;- 遍历原字符数组时,仅修改奇数索引的位置,偶数索引的字符保持不变。
内容的提问来源于stack exchange,提问作者techmcmillie
相关产品推荐
相关产品推荐

