#convert character to string

1 messages · Page 1 of 1 (latest)

harsh timber
#

How can I loop through characters as strings from "A" to "Z"?

I've tried numerous variations of something like:

    var c: u8 = 'A';
    var str: []u8 = "A";
    while (c < 128) : (c += 1) {
        str[0] = c;
onyx patrol
#
    var str = "A".*;
    while (str[0] <= 'Z') : (str[0] += 1) {
gaunt jungle
#

why not just

for (‘A’..’Z’+1) |c| {
    const str = &.{c};
}
harsh timber
#

Hmm, I managed var str = [_]u8{'A'}; and then when I pass as string to a function, I must send the address &str (to pretend it's const?).

gaunt jungle
#

it is const

clever root
clever root
gaunt jungle
#

but you can just do const str: []const u8 = &.{‘A’}

harsh timber
#

one sec, I'magonna try all of your suggestions 🙂

gaunt jungle
clever root
#

the summary is that you need to make some type of arrray and take the address of that, it will coerce to a slice

harsh timber
harsh timber
gaunt jungle
harsh timber
#

🙂 score iterates over the chars of the string returning a scrable score. 'a" = 1 point and 'z' = 10 points.

#

pub fn score(s: []const u8) u32 {

gaunt jungle
#

if score takes a []const u8, it should be called with score(jodi)
otherwise youre giving it a reference to a slice

#

(fwiw, jodi here isnt necessarily a []const u8, but it should be able to coerce for you)

onyx patrol
#

usize doesn't coerce to u8

harsh timber
#

Are these equiv?

var str = [_]u8{'A'};
var str = "A".*;
onyx patrol
#

the first has no null terminator, the second has a null terminator

#

[1]u8 vs [1:0]u8

harsh timber
#

and zig wiil just "do the right thing" when iterating over?

#

seems so

onyx patrol
#

it iterates over str.len which does not include the terminator