我只是想知道是否有任何方法从另一个字符串删除字符串? 就像这样:
class String
def remove(s)
self[s.length, self.length - s.length]
end
end
我只是想知道是否有任何方法从另一个字符串删除字符串? 就像这样:
class String
def remove(s)
self[s.length, self.length - s.length]
end
end
当前回答
你可以使用切片方法:
a = "foobar"
a.slice! "foo"
=> "foo"
a
=> "bar"
有一个非!的版本。更多信息可以在其他版本的文档中看到: http://www.ruby-doc.org/core/classes/String.html#method-i-slice-21
其他回答
你可以使用切片方法:
a = "foobar"
a.slice! "foo"
=> "foo"
a
=> "bar"
有一个非!的版本。更多信息可以在其他版本的文档中看到: http://www.ruby-doc.org/core/classes/String.html#method-i-slice-21
如果你使用的是Rails,也可以删除。
如。"Testmessage".remove("message")输出"Test"。
警告:此方法删除所有发生的事件
如果它是字符串的结尾,你也可以使用chomp:
"hello".chomp("llo") #=> "he"
str.gsub("subString", "")呢? 看看Ruby Doc
我会这么做
2.2.1 :015 > class String; def remove!(start_index, end_index) (end_index - start_index + 1).times{ self.slice! start_index }; self end; end;
2.2.1 :016 > "idliketodeleteHEREallthewaytoHEREplease".remove! 14, 32
=> "idliketodeleteplease"
2.2.1 :017 > ":)".remove! 1,1
=> ":"
2.2.1 :018 > "ohnoe!".remove! 2,4
=> "oh!"
格式化成多行:
class String
def remove!(start_index, end_index)
(end_index - start_index + 1).times{ self.slice! start_index }
self
end
end