在 Ruby 中反转字符串 [英] Reverse a string in Ruby

查看:43
本文介绍了在 Ruby 中反转字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Ruby 中反转字符串?我知道字符串#reverse.我有兴趣了解如何用纯 Ruby 编写它,最好是就地解决方案.

How do you reverse a string in Ruby? I know about string#reverse. I'm interested in understanding how to write it in pure Ruby, preferably an in-place solution.

推荐答案

已经有一个 inplace reverse 方法,叫做reverse!":

There's already an inplace reverse method, called "reverse!":

$ a = "abc"
$ a.reverse!
$ puts a
cba

如果您想手动执行此操作,请尝试此操作(但它可能不是多字节安全的,例如 UTF-8),它会更慢:

If you want to do this manually try this (but it will probably not be multibyte-safe, eg UTF-8), and it will be slower:

class String
  def reverse_inplace!
    half_length = self.length / 2
    half_length.times {|i| self[i], self[-i-1] = self[-i-1], self[i] }
    self
  end
end

这会将开头的每个字节与结尾的每个字节交换,直到两个索引在中心相遇:

This swaps every byte from the beginning with every byte from the end until both indexes meet at the center:

$ a = "abcd"
$ a.reverse_inplace!
$ puts a
dcba

这篇关于在 Ruby 中反转字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆