AzLearn

تمرين إعادة البناء

Text Table Printer

أعد كتابة طابع جدول نصي يحاذي الأعمدة من بيانات مفصولة بفواصل.

rust ~18 دقيقة متوسط
أعد بناء الكود Rebuild

هذا هو الكود. اكتبه بنفسك.

الكود المرجعي
use std::env;
use std::fs;
use std::io::{self, Read};

fn main() -> io::Result<()> {
    let data = match env::args().nth(1) {
        Some(path) => fs::read_to_string(path)?,
        None => {
            let mut input = String::new();
            io::stdin().read_to_string(&mut input)?;
            if input.trim().is_empty() {
                "Name,City,Orders\nAisha,Riyadh,12\nOmar,Jeddah,7\nSara,Dammam,19\n".to_string()
            } else {
                input
            }
        }
    };

    let rows: Vec<Vec<String>> = data
        .lines()
        .map(|line| line.split(',').map(|cell| cell.trim().to_string()).collect())
        .collect();

    print_table(&rows);
    Ok(())
}

fn print_table(rows: &[Vec<String>]) {
    if rows.is_empty() {
        return;
    }

    let columns = rows.iter().map(Vec::len).max().unwrap_or(0);
    let mut widths = vec![0usize; columns];

    for row in rows {
        for (index, cell) in row.iter().enumerate() {
            widths[index] = widths[index].max(cell.chars().count());
        }
    }

    for row in rows {
        for (index, width) in widths.iter().enumerate() {
            let cell = row.get(index).map(String::as_str).unwrap_or("");
            print!("{cell:<width$}  ");
        }
        println!();
    }
}
اكتب هنا