如何在 Nim 中将单个字符转换为字符串?

How to convert from single character to string in Nim?

在Nim中,我有一个字符串需要拆分成字符,但每个字符都应该转换成一个字符串。

现在我有这样的东西:

var d = initTable[string,int]()
for ch in line:
   d.mgetOrPut(ch, 0) += 1

这失败了,因为 ch 是一个字符,而不是一个字符串。一种选择是用 char,int 调用 initTable,但我想知道:如何将上面示例中的 ch 转换为字符串,以便可以将其放入 table?

您可以使用$,例如:

import tables
from strformat import fmt

var line = "abc"
var table = {
  "a": 2,
  "b": 4,
  "c": 8
}.toTable


for x in line:
  # you can use '$' to convert the char 'x' into
  # a single character string
  # ref: https://nim-lang.org/docs/dollars.html#%24%2Cchar
  echo fmt"{x} is {table[$x]}"

引用https://nim-lang.org/docs/dollars.html#%24%2Cchar