Home > OS >  How to remove UTF-8 escape characters generated by String::from_utf8([u8])?
How to remove UTF-8 escape characters generated by String::from_utf8([u8])?

Time:08-29

I have spent the last few hours trying to understand why String::from_utf8 includes escape characters e.g. "u/{x}" when converting from an array of bytes. This is from the Minesweeper exercise on Exercism which encourages the use of bytes over chars for efficiency https://exercism.org/tracks/rust/exercises/minesweeper

I apologize if I use any bad practices, I'm new to Rust

pub fn annotate(minefield: &[&str]) -> Vec<String> {
    const BOMB_COUNT_INDEXES: [(isize, isize); 8] = [
        (-1, -1), (-1, 0), (-1, 1), 
        (0,  -1), /* · */  (0,  1), 
        (1,  -1), (1,  0), (1,  1)
    ];
    minefield.iter()
        .enumerate()
        .map(|(row_n, row_str)| {
            String::from_utf8(
                row_str.as_bytes()
                    .iter()
                    .enumerate()
                    .map(|(column_n, column_byte)| {
                        if *column_byte != b'*' {
                            let mut bombs_n: u8 = 0;
                            for (x, y) in BOMB_COUNT_INDEXES {
                                if let Some(&row) = minefield.get((row_n as isize   x) as usize) {
                                    if let Some(&c) = row.as_bytes().get((column_n as isize   y) as usize) {
                                        if c == b'*' { bombs_n  = 1; }
                                    }
                                }
                            }
                            if bombs_n > 0 { return bombs_n }
                        }
                    return *column_byte
                }).collect::<Vec<u8>>()
            ).unwrap()
        }).collect()
}

CodePudding user response:

You are summing up the surrounding bombs into bombs_n. However, if you have 3 bombs, that is not the same as displaying the character '3'; '3' is represented in ASCII as 51.

You need to do something like:

if bombs_n > 0 { return bombs_n   b'0' }

Or you can use char::from_digit if you're feeling fancy.

  • Related