Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

V: iterate the characters (runes) of a string

Tags:

vlang

According to my understanding, a string in V is wrapped around a byte array encoded as UTF-8. That way, iterating over all string elements returns the bytes:

fn main() {
    s := 'a string with äöü (umlauts)'
    println(s)
    for i := 0; i < s.len; i++ {
        print('-')
    }
    println('')
}

resulting in (note the longer underlining):

a string with äöü (umlauts)
------------------------------

How to get the length of the string in characters/runes? How to iterate over all characters/runes instead of bytes?

like image 285
Thomas S. Avatar asked Oct 29 '25 15:10

Thomas S.


2 Answers

You can call .runes() method on strings. This returns array of runes.

The following code demonstrates converting string to array of runes and then prints its type and lenght.

fn runes_demo(s string) {
    println(s)
    // Iterate over runes of string
    for _ in s.runes() {
        print('_')
    }
    println('')
    println('Return type of runes(): ${typeof(s.runes()).name}')
    println('Length of string in runes: $s.runes().len')
    println('')
}

fn main() {
    s := 'a string with äöü (umlauts)'
    runes_demo(s)
    t := 'hello there!'
    runes_demo(t)
}

This outputs the following:

a string with äöü (umlauts)
___________________________
Return type of runes(): []rune
Length of string in runes: 27

hello there!
____________
Return type of runes(): []rune
Length of string in runes: 12


like image 105
navule Avatar answered Oct 31 '25 12:10

navule


It looks like one needs to use the encoding.utf8 module:

import encoding.utf8

fn main() {
    s := 'a string with äöü (umlauts)'
    println(s)
    for i := 0; i < utf8.len(s); i++ {
        print('-')
    }
    println('')
}
like image 22
Thomas S. Avatar answered Oct 31 '25 13:10

Thomas S.