I have a file in the csv format with a first column of data that represents item code optionally ended with "UNIUNI"
or mixed case of these chars, loaded by means of a barcode reader. I need to trim away the last "UNI"
s.
In Rust I tried to write with partial success a function essentially like this:
fn main() {
// Ok: from "9846UNIUNI" to "9846"
println!("{}", read_csv_rilev("9846UNIUNI".to_string()));
// Wrong: from "9846uniuni" to "9846"
println!("{}", read_csv_rilev("9846uniuni".to_string()));
}
fn read_csv_rilev(code: String) -> String {
code
//.to_uppercase() /*Unstable feature in Rust 1.1*/
.trim_right_matches("UNI")
.to_string()
}
The ideal function signature looks like:
fn read_csv_rilev(mut s: &String) {/**/}
but probably an in-place action on a String is not a good idea. In fact, in the Rust standard library there isn't anything to do this excluding String::pop()
.
Is there a way to apply the trimming on a String without to allocate another one?
Yes, using
truncate
:Of course, you don't need to mess with the allocated string at all. You can use the same logic and make successive subslices of the string. This is basically how
trim_right_matches
works, but a bit less generic:In general, I'd probably go with the second solution.
The binding is mutable in
mut s: &String
, not the string itself. You would takes: &mut String
if you wanted to mutate the string itself.That said, I don't think there's anything in the standard library to do this.
Another solution is to use the
owning_ref
crate, which lets you return both a&str
and its backingString
at the same time: