How to convert a string into a sequence of characters in Nim?
This tutorial explains how to convert a String into a Sequence of characters in the Nim Programming language
The string is a type that contains a collection of characters, enclosed in double quotes.
The sequence is a collection of elements with dynamic in size.
Both are different data types and automatic conversion is not required.
Convert String into a sequence of characters in Nim with an example
Multiple ways we can convert a String into a sequence
- sequtils module toSeq procedure
The sequtils
module contains the toSeq
procedure to convert the iterated types into a sequence.
First, convert String into iterate using items Here is an examples
import sequtils
var str="example"
var sequence=toSeq(str.items)
echo sequence
echo typeof(sequence)
Output:
@['e', 'x', 'a', 'm', 'p', 'l', 'e']
seq[char]
- use sequtils map procedure
map
is a procedure that is used with a lambda expression to iterate the elements and returns the sequence of elements.
Example:
import sequtils,sugar
var str="example"
var sequence1 = str.map(c => c)
echo sequence1
echo typeof(sequence1)
Output:
@['e', 'x', 'a', 'm', 'p', 'l', 'e']
seq[char]
- use sequtils map procedure
@ operator
converts a string to the sequence. You can also use an array to sequence with this.
Here is an example
import sequtils,sugar
var str="example"
var sequence1 = @str
echo sequence1
echo typeof(sequence1)
- use cast operator
cast
allows you to convert one type to another type
cast[targettype](data)
It converts given variable data to target data type, in this case seq[char]
.
Here is an example
import sequtils
var str="example"
var sequence=cast[seq[char]](str)
echo sequence
echo typeof(sequence)