基本上问题是什么.如何删除字符串中给定索引位置的字符?String类似乎没有任何方法可以执行此操作.
如果我有一个字符串"HELLO"我希望输出是这样的
["ELLO", "HLLO", "HELO", "HELO", "HELL"]
Run Code Online (Sandbox Code Playgroud)
我这样做
d = Array.new(c.length){|i| c.slice(0, i)+c.slice(i+1, c.length)}
Run Code Online (Sandbox Code Playgroud)
我不知道是否使用切片!会在这里工作,因为它会修改原始字符串,对吗?
Ber*_*rry 10
不会Str.slice!做到了吗?来自ruby-doc.org:
str.slice!(fixnum)=> fixnum或nil [...]
Run Code Online (Sandbox Code Playgroud)Deletes the specified portion from str, and returns the portion deleted.
如果您使用的是Ruby 1.8,则可以使用delete_at(从Enumerable中混入),否则在1.9中可以使用slice!.
例:
mystring = "hello"
mystring.slice!(1) # mystring is now "hllo"
# now do something with mystring
Run Code Online (Sandbox Code Playgroud)
$ 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"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14829 次 |
| 最近记录: |