将seq [char]转换为字符串

问题描述 投票:13回答:3

我有一个seq[char]的情况,像这样:

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

s转换回字符串(即"abc")的最佳方法是什么?用$进行字符串化似乎给了"@[a, b, c]",这不是我想要的。

nim
3个回答
11
投票

最有效的方法是编写自己的程序。

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)

6
投票
import sequtils, strutils
var s: seq[char] = toSeq("abc".items)
echo(s.mapIt(string, $it).join)

加入仅适用于seq[string],因此您必须先将其映射到字符串。


0
投票

您也可以尝试使用强制转换:

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
© www.soinside.com 2019 - 2024. All rights reserved.