nim-lang

How to insert a character into a string in Nim


I need to insert a character into a string, knowing the insertion index. Can I do this without resorting to concatenation?

Before:

001D0FF180B2

After:

001D0FF180:B2

Solution

  • You can do that using system.insert:

    var s = "001D0FF180B2"
    s.insert(":", 10)
    echo s  # 001D0FF180:B2
    

    Or sugar.dup if you don't want to do that in-place:

    echo "001D0FF180B2".dup(insert(":", 10))  # 001D0FF180:B2