Sebastian
Sebastian

Reputation: 2279

How do I convert a string into a sequence of characters in Nim?

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

Answers (7)

slobin
slobin

Reputation: 31

@ converts both arrays and strings to sequences:

echo @"abc"

Output: @['a', 'b', 'c']

Upvotes: 3

Victor Yan
Victor Yan

Reputation: 3509

The simplest way to do this:

import sequtils
echo "ab".toSeq()

Upvotes: 0

whiterock
whiterock

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

Jim Balter
Jim Balter

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

Kaushal Modi
Kaushal Modi

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

Jabba
Jabba

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

Andrew Penkrat
Andrew Penkrat

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

Related Questions