Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

nim-lang

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

like image 449
Sebastian Avatar asked Jun 14 '18 08:06

Sebastian


People also ask

How to convert a delimited string to a sequence of strings?

To convert a delimited string to a sequence of strings in C#, you can use the String.Split () method. Since the Split () method returns a string array, you can convert it into a List using the ToList () method. You need to include the System.Linq namespace to access the ToList () method.

How do I get an array of the characters in a string?

This example shows how you can get an array of the characters in a string by calling the string's ToCharArray method. This example demonstrates how to split a string into a Char array, and how to split a string into a String array of its Unicode text characters.

How do you loop through a string of characters?

When looping over the characters in a string you’ll normally use the map or foreach methods, but if for some reason those approaches won’t work for your situation, you can treat a String as an Array, and access each character with the array notation shown.

Why are alphanumeric characters stored in wide strings in C++?

In Modern C++, alphanumeric characters are stored in wide strings because of their supports to characters of world languages and displayed in wstring forms. In another terms wstring stores for the alphanumeric text with 2 byte chars, called wchar_t or WChar.


3 Answers

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

like image 27
Jabba Avatar answered Sep 24 '22 19:09

Jabba


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)
like image 52
Andrew Penkrat Avatar answered Sep 26 '22 19:09

Andrew Penkrat


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

like image 43
Kaushal Modi Avatar answered Sep 23 '22 19:09

Kaushal Modi