我有几个字符串,如下所示:
"((String1))"
Run Code Online (Sandbox Code Playgroud)
它们都是不同的长度.如何在循环中从所有这些字符串中删除括号?
Aru*_*hit 152
使用以下操作String#tr:
"((String1))".tr('()', '')
# => "String1"
Run Code Online (Sandbox Code Playgroud)
jbr*_*jbr 38
如果您只想删除前两个字符和后两个字符,那么您可以在字符串上使用负索引:
s = "((String1))"
s = s[2...-2]
p s # => "String1"
Run Code Online (Sandbox Code Playgroud)
如果要从字符串中删除所有括号,可以在字符串类上使用delete方法:
s = "((String1))"
s.delete! '()'
p s # => "String1"
Run Code Online (Sandbox Code Playgroud)
fal*_*tru 19
使用String#gsub正则表达式:
"((String1))".gsub(/^\(+|\)+$/, '')
# => "String1"
"(((((( parentheses )))".gsub(/^\(+|\)+$/, '')
# => " parentheses "
Run Code Online (Sandbox Code Playgroud)
这将仅删除周围的括号.
"(((((( This (is) string )))".gsub(/^\(+|\)+$/, '')
# => " This (is) string "
Run Code Online (Sandbox Code Playgroud)
dai*_*no3 14
对于那些遇到这种情况并寻找性能的人来说,它看起来#delete和#tr速度差不多,速度快2-4倍gsub.
text = "Here is a string with / some forwa/rd slashes"
tr = Benchmark.measure { 10000.times { text.tr('/', '') } }
# tr.total => 0.01
delete = Benchmark.measure { 10000.times { text.delete('/') } }
# delete.total => 0.01
gsub = Benchmark.measure { 10000.times { text.gsub('/', '') } }
# gsub.total => 0.02 - 0.04
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
148864 次 |
| 最近记录: |