删除Ruby中索引位置的字符

问题描述 投票:8回答:5

基本上问题是什么。如何删除字符串中给定索引位置的字符? String类似乎没有任何方法可以执行此操作。

如果我有一个字符串“HELLO”我希望输出是这样的

["ELLO", "HLLO", "HELO", "HELO", "HELL"]

我这样做

d = Array.new(c.length){|i| c.slice(0, i)+c.slice(i+1, c.length)}

我不知道是否使用切片!会在这里工作,因为它会修改原始字符串,对吗?

ruby
5个回答
4
投票
$ cat m.rb
class String
  def maulin! n
    slice! n
    self
  end
  def maulin n
    dup.maulin! n
  end
end
$ irb
>> require 'm'
=> true
>> s = 'hello'
=> "hello"
>> s.maulin(2)
=> "helo"
>> s
=> "hello"
>> s.maulin!(1)
=> "hllo"
>> s
=> "hllo"

10
投票

不会Str.slice!做到了吗?来自ruby-doc.org:

str.slice!(fixnum)=> fixnum或nil [...]

 Deletes the specified portion from str, and returns the portion deleted.

7
投票

如果您使用的是Ruby 1.8,则可以使用delete_at(从Enumerable中混入),否则在1.9中可以使用slice!。

例:

mystring = "hello"
mystring.slice!(1)  # mystring is now "hllo"
# now do something with mystring

2
投票

为了避免需要猴子补丁String你可以使用tap

"abc".tap {|s| s.slice!(2) }
=> "ab"

如果您需要保持原始字符串不变,请使用dup,例如。 abc.dup.tap


1
投票

我做了这样的事

c.slice(0, i)+c.slice(i+1, c.length)

其中c是字符串,i是我想要删除的索引位置。有没有更好的办法?

© www.soinside.com 2019 - 2024. All rights reserved.