7

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?)

Sebastian
  • 2,249
  • 17
  • 20

7 Answers7

8

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)
Andrew Penkrat
  • 447
  • 4
  • 11
5

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.

whiterock
  • 190
  • 2
  • 11
4

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'].

Jabba
  • 19,598
  • 6
  • 52
  • 45
  • 1
    List comprehensions are deprecated since version 0.19.9. – danlei Aug 17 '19 at 16:26
  • @danlei: So, what do you suggest instead? – Jabba Oct 06 '19 at 13:48
  • Well, you could use a library like [comprehension](https://github.com/alehander42/comprehension) or maybe [for loop macros](https://nim-lang.org/docs/manual.html#macros-for-loop-macro), but I haven't used them myself, so you'd have to check them out yourself. – danlei Oct 06 '19 at 18:00
4

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'].

Kaushal Modi
  • 1,258
  • 2
  • 20
  • 43
2

A string already is a sequence of chars:

assert "ab" == @['a', 'b']

import sequtils
assert "ab".mapIt(it.ord) == @[97, 98]

Jim Balter
  • 16,163
  • 3
  • 43
  • 66
0

The simplest way to do this:

import sequtils
echo "ab".toSeq()
Victor Yan
  • 3,339
  • 2
  • 28
  • 28
0

@ converts both arrays and strings to sequences:

echo @"abc"

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

slobin
  • 1