This program creates a byte array (containing bytes for the letters "cats") and then creates 2 Vectors from the bytes array. We use from() and clone() to create the Vectors.
use std::str;
fn main() {
let bytes = *b
"cats";
let bytes_vec = Vec::from(&bytes);
let bytes_vec2 = bytes_vec.clone();
// Part 1: use String from_utf8 with vector of bytes.
if let Ok(value) = String::from_utf8(bytes_vec) {
println!(
"{} {} {}", value, value.len(), value.to_uppercase());
}
// Part 2: use str from_utf8 on a byte slice.
if let Ok(value) = str::from_utf8(&bytes) {
println!(
"{} {} {}", value, value.len(), value.to_uppercase());
}
// Part 3: use str from_utf8 on another slice.
if let Ok(value) = str::from_utf8(&bytes[0..3]) {
println!(
"{} {} {}", value, value.len(), value.to_uppercase());
}
// Part 4: use String from_utf8_lossy on a byte slice.
let temp = String::from_utf8_lossy(&bytes);
println!(
"{} {} {}", temp, temp.len(), temp.to_uppercase());
// Part 5: get actual String from from_utf8_lossy.
let temp2 = String::from_utf8_lossy(&bytes).to_string();
println!(
"{} {} {}", temp2, temp2.len(), temp2.to_uppercase());
// Part 6: use String from utf8_unchecked on vector of bytes.
unsafe {
let value = String::from_utf8_unchecked(bytes_vec2);
println!(
"{} {} {}", value, value.len(), value.to_uppercase());
}
}
cats 4 CATS
cats 4 CATS
cat 3 CAT
cats 4 CATS
cats 4 CATS
cats 4 CATS