Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a seq[char] to string

Tags:

nim-lang

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.

like image 967
Sp3000 Avatar asked Aug 19 '15 11:08

Sp3000


2 Answers

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)
like image 73
Reimer Behrends Avatar answered Sep 20 '22 15:09

Reimer Behrends


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.

like image 32
Reactormonk Avatar answered Sep 17 '22 15:09

Reactormonk