在 Nim 中,我有一个字符串,需要将其拆分为字符,但每个字符都应转换为字符串。
现在我有类似的东西:
var d = initTable[string,int]()
for ch in line:
d.mgetOrPut(ch, 0) += 1
Run Code Online (Sandbox Code Playgroud)
这失败了,因为ch是一个字符,而不是一个字符串。一种选择是调用initTablewith char,int,但我想知道:如何将ch上面的示例转换为字符串,以便将其放入表中?
您可以使用$,例如:
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]}"
Run Code Online (Sandbox Code Playgroud)
参考 https://nim-lang.org/docs/dollars.html#%24%2Cchar
| 归档时间: |
|
| 查看次数: |
2738 次 |
| 最近记录: |