You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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。

实现思路

核心思路是分离出原字符串中奇数索引的字符,反转这部分字符后,再将它们按顺序放回原字符串的奇数索引位置:

  1. 提取原字符串所有奇数索引的字符,组成数组并反转;
  2. 遍历原字符串的每个字符,遇到奇数索引时,用反转后的奇数字符数组依次替换;
  3. 最后将处理后的字符数组拼接成字符串。

代码实现

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 19:06:28