Converting a seq[char] to string
Asked Answered
E

3

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.

Expensive answered 19/8, 2015 at 11:43 Comment(0)
S
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)
Separate answered 19/8, 2015 at 19:41 Comment(0)
C
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.

Chlorine answered 19/8, 2015 at 12:30 Comment(2)
mapIt is now deprecated in favor of applyIt: github.com/nim-lang/Nim/pull/3372/filesGalvanism
mapIt still works for this, but I don't think you need to type: play.nim-lang.org/#ix=2IPELiselisetta
C
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
Cymar answered 29/8, 2018 at 16:50 Comment(2)
a string is not binary equivalent to a seq[char], it contains an extra null byte, for compatibility with cstringInsomniac
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.Impeachable

© 2022 - 2024 — McMap. All rights reserved.