Is there a functional/idiomatic way of doing this? Essentially, this iteration is a bit tricky, because I want to:
Iterate through a Vec<String>.
For each element:
Split the string into components separated by periods;
Capitalize each component; and
Merge all the components back into a Pascal-cased string.
Print each element.
I thought of making one iterator, and then in a map() closure I'd build yet another iterator, return that, and so on, but that seems cluttery and is quite confusing. I could always just use a standard for loop but I was wondering if this was a common enough thing that people had come up with a more idiomatic way of doing it already.
Constant indexing on UTF-8 string is dangerous - it may panic on non-ascii character. Consider some popular case conversion crate instead, like heck.
use heck::CamelCase; // `heck` calls it CamelCase - check its docs.
fn main() {
let b = vec![
"very.juicy.parenchyma".to_string(),
"can.coagulate.rapidly".into(),
"blocking.the.stromata".into(),
"외국어.문자열".into(),
];
for el in &b {
let el: String = el.split('.')
.map(str::to_camel_case)
.collect();
println!("{}", el);
}
}
Could you clarify on this? How could constant indexing on a string panic on a non-ASCII character? Doesn't the Index trait implementation on Strings just call the String::get method?
fn main() {
let s = "외국어.문자열".to_string();
println!("{}", &s[1..]);
}
// thread 'main' panicked at 'byte index 1 is not a char boundary;
// it is inside '외' (bytes 0..3) of `외국어.문자열`', src/main.rs:3:21