How to convert from single character to string in Nim?
Asked Answered
P

1

6

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?

Parous answered 2/12, 2018 at 11:56 Comment(0)
S
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

Smooth answered 2/12, 2018 at 16:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.