有没有办法在不分配另一个字符串的情况下修剪字符串? [英] Is there a way to trim a String without allocating another one?

查看:20
本文介绍了有没有办法在不分配另一个字符串的情况下修剪字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 CSV 格式的文件,其中第一列数据代表商品代码,可选地以 UNIUNI" 或这些字符的混合大小写结尾,通过条形码阅读器加载.我需要剪掉最后的 "UNI" s.

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.

我写了这个函数:

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()
}

理想的函数签名如下:

fn read_csv_rilev(mut s: &String)

但可能对 String 的就地操作不是一个好主意.事实上,在 Rust 标准库中,除了 String::pop() 之外,没有任何东西可以做到这一点.

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().

推荐答案

有没有办法在不分配另一个String的情况下修剪String?

是的,您可以使用 truncate 删除字符串的尾随部分:

Yes, you can use truncate to remove trailing parts of the string:

const TRAILER: &'static str = "UNI";

fn read_csv_rilev(s: &mut String) {
    while s.ends_with(TRAILER) {
        let len = s.len();
        let new_len = len.saturating_sub(TRAILER.len());
        s.truncate(new_len);
    }
}

fn main() {
    let mut code = "Hello WorldUNIUNIUNI".into();
    
    read_csv_rilev(&mut code);
    
    assert_eq!("Hello World", code);
}

您根本不需要弄乱分配的字符串.您可以使用相同的逻辑并制作字符串的连续子切片.这基本上是 trim_right_matches 的工作方式,但不太通用:

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:

const TRAILER: &'static str = "UNI";

fn read_csv_rilev(mut s: &str) -> &str {
    while s.ends_with(TRAILER) {
        let len = s.len();
        let new_len = len.saturating_sub(TRAILER.len());
        s = &s[..new_len];
    }
    s
}

fn main() {
    let code = "Hello WorldUNIUNIUNI";

    let truncated = read_csv_rilev(code);

    assert_eq!("Hello World", truncated);
}

一般来说,我可能会选择第二种解决方案.

In general, I'd probably go with the second solution.

这篇关于有没有办法在不分配另一个字符串的情况下修剪字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆