Write Rust program similar to tr util, that reads two char arrays as arguments and replaces in stdin chars from first array to chars from second array.
Assistant
Certainly! Below is a Rust program that mimics the functionality of the tr utility, which translates characters from one set to another. The program reads two input character arrays and replaces characters from the first array with the corresponding characters from the second array based on the mappings you specify in the command line arguments.
Here is a simple implementation:
rust
use std::env;
use std::io::{self, BufRead};
fn main() {
// Collect command line arguments
let args: Vec<String> = env::args().collect();
// Ensure we have exactly two arguments
if args.len() != 3 {
eprintln!("Usage: {} <set1> <set2>", args[0]);
std::process::exit(1);
}
let set1 = &args[1];
let set2 = &args[2];
// Check that both character sets are of the same length
if set1.len() != set2.len() {
eprintln!("The sets must be of equal length.");
std::process::exit(1);
}
// Create a mapping of characters from set1 to set2
let translation_map: std::collections::HashMap<char, char> = set1.chars().zip(set2.chars()).collect();
// Read from stdin and perform the translation
let stdin = io::stdin();
for line in stdin.lock().lines() {
let line = line.unwrap();
let translated_line: String = line.chars()
.map(|c| translation_map.get(&c).unwrap_or(&c))
.collect();
println!("{}", translated_line);
}
}
Explanation:
Command Line Arguments: The program expects two arguments on the command line: set1 and set2. Each character in set1 will be replaced with the corresponding character in set2.
Length Check: The program checks if both sets are of equal length. If not, it prints an error message and exits.
Translation Map: A mapping between characters in set1 and set2 is created using a hash map.
Reading from Standard Input: The program uses standard input to read lines. Each character from each line is checked against the translation map, and if a match is found, it gets replaced. If there’s no match, it remains unchanged.
Output: Translated lines are printed to the standard output.
How to Use:
To use this program, you can compile it using rustc and then run it, passing the two character sets as arguments. For example:
bash
$ rustc tr.rs
$ ./tr abc xyz
Then, you can input text via standard input:
code
abc 123
abacaba
You should see:
code
xyz 123
xyzyxyz
This implementation translates characters but doesn’t handle edge cases like ASCII values beyond the specified character sets or non-matching length for argument sets. You can expand this as needed based on your specific use case.