如何在 Nim 中将字符串转换为字符序列?

Seb*_*ian 6 nim-lang

我想对字符串中的字符执行不同的操作,例如 map 或 reverse。作为第一步,我想将字符串转换为序列。

给定一个像“ab”这样的字符串。我如何得到一个序列@['a','b']

"ab".split("") 返回整个字符串。

我之前看过一个例子"ab".items,但这似乎不起作用(是否已弃用?)

And*_*rat 6

items is an iterator, not a function, so you can only call it in a few specific contexts (like for loop). However, you can easily construct a sequence from an iterator using toSeq from sequtils module (docs). E.g.:

import sequtils
echo toSeq("ab".items)
Run Code Online (Sandbox Code Playgroud)


whi*_*ock 5

因为string像简单的强制转换一样实现就seq[char]足够了,即

echo cast[seq[char]]("casting is formidable")
Run Code Online (Sandbox Code Playgroud)

这显然是最有效的方法,因为它只是一个转换,尽管编译器可能对此答案中概述的其他一些方法进行了优化。