csv file, read to string and split by lines, how to sort it by filed in rust

main.rs
use std::error::Error;
use std::fs::File;
use std::io::{BufRead, BufReader};

fn read_csv_to_string(filename: &str) -> Result<String, Box<dyn Error>> {
    let file = File::open(filename)?;
    let reader = BufReader::new(file);
    let mut csv_string = String::new();

    for line in reader.lines() {
        csv_string.push_str(&line?);
        csv_string.push('\n');
    }

    Ok(csv_string)
}

fn sort_csv_by_field(csv_string: &str, field_index: usize, delimiter: char) -> Vec<String> {
    let mut lines: Vec<String> = csv_string.lines().map(|line| line.to_string()).collect();

    lines.sort_by(|a, b| {
        let a_fields: Vec<&str> = a.split(delimiter).collect();
        let b_fields: Vec<&str> = b.split(delimiter).collect();

        a_fields[field_index].cmp(&b_fields[field_index])
    });

    lines
}

fn main() {
    if let Ok(csv_content) = read_csv_to_string("data.csv") {
        let sorted_lines = sort_csv_by_field(&csv_content, 0, ',');

        for line in sorted_lines {
            println!("{}", line);
        }
    } else {
        eprintln!("Error reading the CSV file");
    }
}
1114 chars
42 lines

This code snippet demonstrates how to read a CSV file into a string, split it by lines, and then sort it by a specific field in Rust. Make sure to replace "data.csv" with the actual path to your CSV file.

related categories

gistlibby LogSnag