16

I'm in a situation where I have a seq[char], like so:

import sequtils
var s: seq[char] = toSeq("abc".items)

What's the best way to convert s back into a string (i.e. "abc")? Stringifying with $ seems to give "@[a, b, c]", which is not what I want.

Sp3000
  • 374
  • 2
  • 10

3 Answers3

13

The most efficient way is to write a procedure of your own.

import sequtils
var s = toSeq("abc".items)

proc toString(str: seq[char]): string =
  result = newStringOfCap(len(str))
  for ch in str:
    add(result, ch)

echo toString(s)
Reimer Behrends
  • 8,600
  • 15
  • 19
8
import sequtils, strutils
var s: seq[char] = toSeq("abc".items)
echo(s.mapIt(string, $it).join)

Join is only for seq[string], so you'll have to map it to strings first.

Reactormonk
  • 21,472
  • 14
  • 74
  • 123
  • `mapIt` is now deprecated in favor of `applyIt`: https://github.com/nim-lang/Nim/pull/3372/files – Dave Yarwood Feb 13 '17 at 15:58
  • `mapIt` still works for this, but I don't think you need to type: https://play.nim-lang.org/#ix=2IPE – Tom Dec 20 '20 at 09:31
2

You could also try using a cast:

var s: seq[char] = @['A', 'b', 'C']
var t: string = cast[string](s)
# below to show that everything (also resizing) still works:
echo t
t.add('d')
doAssert t.len == 4
echo t
for x in 1..100:
  t.add('x')
echo t.len
echo t
  • a string is not binary equivalent to a seq[char], it contains an extra null byte, for compatibility with cstring – shirleyquirk Oct 25 '21 at 22:43
  • This seems to work, but be careful of casting. I made the mistake of doing `cast[string](['x'])` which segfaults, because I left out the `@` to convert an array to a seq. – Desty Feb 05 '22 at 03:07