5

In Nim, I have a string that I need to split into characters, but each character should be converted to a string.

Right now I have something like:

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

This fails, because ch is a character, not a string. One option is to call initTable with char,int, but I would like to know: how can I convert ch in the example above to a string, so that it can be put into the table?

Herman Schaaf
  • 46,821
  • 21
  • 100
  • 139

1 Answers1

6

You can use $, for example:

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]}"

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

cyraxjoe
  • 5,661
  • 3
  • 28
  • 42