How to resolve the algorithm Letter frequency step by step in the Rust programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Letter frequency step by step in the Rust programming language

Table of Contents

Problem Statement

Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Letter frequency step by step in the Rust programming language

Source code in the rust programming language

use std::collections::btree_map::BTreeMap;
use std::{env, process};
use std::io::{self, Read, Write};
use std::fmt::Display;
use std::fs::File;

fn main() {
    let filename = env::args().nth(1)
        .ok_or("Please supply a file name")
        .unwrap_or_else(|e| exit_err(e, 1));

    let mut buf = String::new();
    let mut count = BTreeMap::new();

    File::open(&filename)
        .unwrap_or_else(|e| exit_err(e, 2))
        .read_to_string(&mut buf)
        .unwrap_or_else(|e| exit_err(e, 3));


    for c in buf.chars() {
        *count.entry(c).or_insert(0) += 1;
    }

    println!("Number of occurences per character");
    for (ch, count) in &count {
        println!("{:?}: {}", ch, count);
    }
}

#[inline]
fn exit_err<T>(msg: T, code: i32) -> ! where T: Display {
    writeln!(&mut io::stderr(), "{}", msg).expect("Could not write to stderr");
    process::exit(code)
}


  

You may also check:How to resolve the algorithm Runge-Kutta method step by step in the PL/I programming language
You may also check:How to resolve the algorithm Repeat step by step in the Batch File programming language
You may also check:How to resolve the algorithm String length step by step in the Symsyn programming language
You may also check:How to resolve the algorithm Day of the week step by step in the Smalltalk programming language
You may also check:How to resolve the algorithm Loops/Infinite step by step in the GB BASIC programming language