我有一个字符串str = "abcdefghij"
,我想将str2
设置为str减去第4到第6个字符(假设基于0的索引)。
是否有可能一次性完成这项工作? slice!
似乎这样做,但它需要至少3个语句(复制,切片,然后使用字符串)。
答案 0 :(得分:2)
常见的方法是这样做:
str = "abcdefghij"
str2 = str.dup
str2[4..6] = ''
# => "abcdhij"
但仍需要两个步骤。
如果您想要的范围是连续的,那么您可以一步完成
str2 = str[2..5]
# => "cdef"
答案 1 :(得分:1)
根据您要删除的内容,http://ruby-doc.org/core/classes/String.html#M001201可能是一个选项。
你可能会用正则表达式做淫秽的事情:
"abcdefghij".sub(/(.{4}).{2}/) { $1 }
但这很糟糕。
答案 2 :(得分:1)
我继续使用以下内容:
str = "abcdefghij"
str2 = str[0, 4] + str[7..-1]
事实证明,它比其他解决方案更快,更清洁。这是一个迷你基准。
require 'benchmark'
str = "abcdefghij"
times = 1_000_000
Benchmark.bmbm do |bm|
bm.report("1 step") do
times.times do
str2 = str[0, 4] + str[7..-1]
end
end
bm.report("3 steps") do
times.times do
str2 = str.dup
str2[4..6] = ''
str2
end
end
end
Ruby 1.9.2上的输出
Rehearsal -------------------------------------------
1 step 0.950000 0.010000 0.960000 ( 0.955288)
3 steps 1.250000 0.000000 1.250000 ( 1.250415)
---------------------------------- total: 2.210000sec
user system total real
1 step 0.960000 0.000000 0.960000 ( 0.950541)
3 steps 1.250000 0.010000 1.260000 ( 1.254416)
修改:<<
的更新。
脚本:
require 'benchmark'
str = "abcdefghij"
times = 1_000_000
Benchmark.bmbm do |bm|
bm.report("1 step") do
times.times do
str2 = str[0, 4] + str[7..-1]
end
end
bm.report("3 steps") do
times.times do
str2 = str.dup
str2[4..6] = ''
str2
end
end
bm.report("1 step using <<") do
times.times do
str2 = str[0, 4] << str[7..-1]
end
end
end
Ruby 1.9.2上的输出
Rehearsal ---------------------------------------------------
1 step 0.980000 0.010000 0.990000 ( 0.979944)
3 steps 1.270000 0.000000 1.270000 ( 1.265495)
1 step using << 0.910000 0.010000 0.920000 ( 0.909705)
------------------------------------------ total: 3.180000sec
user system total real
1 step 0.980000 0.000000 0.980000 ( 0.985154)
3 steps 1.280000 0.000000 1.280000 ( 1.281310)
1 step using << 0.930000 0.000000 0.930000 ( 0.916511)