julia如何在特定位置插入多个字符?

using BioSequences
julia> a=dna"ATCG"
4nt DNA Sequence:
ATCG
julia> insert!(a,2,'C')
5nt DNA Sequence:
ACTCG

但是我插入多个字符就不可以了

julia> insert!(a,2,"CG")
ERROR: MethodError: Cannot `convert` an object of type String to an object of type DNA

julia> insert!(a,2,dna"CG")
ERROR: MethodError: Cannot `convert` an object of type LongDNASeq to an object of type DNA

如果这样的话就只能字符串拼接了么?或者只能one by one insert 吗?谢谢

要看具体的实现,从源码可以看到只有单个元素的insert!,而根据文档标准库的insert!的含义是插入一个元素,因此其他类型的实现一般相同的功能来。

如果想一次性插入多个,可以参考append!insert!的实现自己写一个函数:

function Base.append!(seq::BioSequence, other::BioSequence)
    resize!(seq, length(seq) + length(other))
    copyto!(seq, lastindex(seq) - length(other) + 1, other, 1, length(other))
    return seq
end
function Base.insert!(seq::BioSequence, i::Integer, x)
    checkbounds(seq, i)
    resize!(seq, length(seq) + 1)
    copyto!(seq, i + 1, seq, i, lastindex(seq) - i)
    @inbounds seq[i] = x
    return seq
end
1 个赞