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

7

8

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

Sitting answered 14/6, 2018 at 8:51 Comment(0)
G
9

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)
Grade answered 14/6, 2018 at 12:44 Comment(0)
S
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.

Skardol answered 24/6, 2020 at 20:41 Comment(0)
G
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'].

Gardol answered 17/6, 2018 at 19:36 Comment(3)
List comprehensions are deprecated since version 0.19.9.Swinton
@danlei: So, what do you suggest instead?Gardol
Well, you could use a library like comprehension or maybe for loop macros, but I haven't used them myself, so you'd have to check them out yourself.Swinton
E
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'].

Erek answered 3/7, 2018 at 17:27 Comment(1)
If you don't want to rely on future or sugar you can use mapIt("abc", it)Billy
T
2

A string already is a sequence of chars:

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

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

Trismus answered 13/6, 2020 at 4:42 Comment(0)
T
1

@ converts both arrays and strings to sequences:

echo @"abc"

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

Theressathereto answered 2/7, 2022 at 14:55 Comment(0)
E
0

The simplest way to do this:

import sequtils
echo "ab".toSeq()
Ewan answered 3/11, 2021 at 7:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.