Reputation: 2279
I want to do different operations with the characters in a string e.g. map or reverse. As a first step I want to convert the string into a sequence.
Given a string like "ab".
How do I get a sequence like @['a','b']
?
"ab".split("")
returns the whole string.
I have seen an example with "ab".items
before, but that doesn't seem to work (is that deprecated?)
Upvotes: 9
Views: 5444
Reputation: 31
@
converts both arrays and strings to sequences:
echo @"abc"
Output: @['a', 'b', 'c']
Upvotes: 3
Reputation: 300
Since string
is implemented like seq[char]
a simple cast suffices, i.e.
echo cast[seq[char]]("casting is formidable")
this is obviously the most efficient approach, since it's just a cast, though perhaps some of the other approaches outlined in the answers here get optimized by the compiler to this.
Upvotes: 5
Reputation: 16406
A string already is a sequence of chars:
assert "ab" == @['a', 'b']
import sequtils
assert "ab".mapIt(it.ord) == @[97, 98]
Upvotes: 2
Reputation: 1370
Here's another variant using map
from sequtils
and =>
from future
(renamed to sugar
on Nim devel):
import sequtils, sugar
echo "nim lang".map(c => c)
Outputs @['n', 'i', 'm', ' ', 'l', 'a', 'n', 'g']
.
Upvotes: 4
Reputation: 20614
You can also use a list comprehension:
import future
let
text = "nim lang"
parts = lc[c | (c <- text), char]
Parts is @['n', 'i', 'm', ' ', 'l', 'a', 'n', 'g']
.
Upvotes: 4
Reputation: 457
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)
Upvotes: 9