在同一字符串上运行多个连续替换 [英] Running a number of consecutive replacements on the same string

查看:40
本文介绍了在同一字符串上运行多个连续替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了这个子字符串替换的例子:

I found this example for substring replacement:

use std::str;
let string = "orange";
let new_string = str::replace(string, "or", "str");

如果我想在同一个字符串上运行多个连续替换,为了清理目的,我该如何做到这一点而不为每个替换分配一个新变量?

If I want to run a number of consecutive replacements on the same string, for sanitization purposes, how can I do that without allocating a new variable for each replacement?

如果您要编写惯用的 Rust,您会如何编写多个链式子字符串替换?

If you were to write idiomatic Rust, how would you write multiple chained substring replacements?

推荐答案

您将如何编写多个链接的子字符串替换?

how would you write multiple chained substring replacements?

我会按照要求去做:

fn main() {
    let a = "hello";
    let b = a.replace("e", "a").replace("ll", "r").replace("o", "d");
    println!("{}", b);
}

如果您问的是如何进行多个并发替换,只通过一次字符串,那么它确实变得很多更难.

It you are asking how to do multiple concurrent replacements, passing through the string just once, then it does indeed get much harder.

这确实需要为每个 replace 调用分配新的内存,即使不需要替换也是如此.replace 的替代实现可能会返回 Cow 仅在发生替换时包含拥有的变体.一个 hacky 实现可能如下所示:

This does require allocating new memory for each replace call, even if no replacement was needed. An alternate implementation of replace might return a Cow<str> which only includes the owned variant when the replacement would occur. A hacky implementation of that could look like:

use std::borrow::Cow;

trait MaybeReplaceExt<'a> {
    fn maybe_replace(self, needle: &str, replacement: &str) -> Cow<'a, str>;
}

impl<'a> MaybeReplaceExt<'a> for &'a str {
    fn maybe_replace(self, needle: &str, replacement: &str) -> Cow<'a, str> {
        // Assumes that searching twice is better than unconditionally allocating
        if self.contains(needle) {
            self.replace(needle, replacement).into()
        } else {
            self.into()
        }
    }
}

impl<'a> MaybeReplaceExt<'a> for Cow<'a, str> {
    fn maybe_replace(self, needle: &str, replacement: &str) -> Cow<'a, str> {
        // Assumes that searching twice is better than unconditionally allocating
        if self.contains(needle) {
            self.replace(needle, replacement).into()
        } else {
            self
        }
    }
}

fn main() {
    let a = "hello";
    let b = a.maybe_replace("e", "a")
        .maybe_replace("ll", "r")
        .maybe_replace("o", "d");
    println!("{}", b);

    let a = "hello";
    let b = a.maybe_replace("nope", "not here")
        .maybe_replace("still no", "i swear")
        .maybe_replace("but no", "allocation");
    println!("{}", b);
    assert_eq!(b.as_ptr(), a.as_ptr());
}

这篇关于在同一字符串上运行多个连续替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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