如何连接字符串?

How do I concatenate strings?

如何连接以下类型组合:

连接字符串时,需要分配内存来存储结果。最容易开始的是 String&str:

fn main() {
    let mut owned_string: String = "hello ".to_owned();
    let borrowed_string: &str = "world";
    
    owned_string.push_str(borrowed_string);
    println!("{}", owned_string);
}

在这里,我们有一个我们可以改变的自有字符串。这是有效的,因为它可能允许我们重用内存分配。 StringString 也有类似的情况,如 &String can be dereferenced as &str.

fn main() {
    let mut owned_string: String = "hello ".to_owned();
    let another_owned_string: String = "world".to_owned();
    
    owned_string.push_str(&another_owned_string);
    println!("{}", owned_string);
}

在此之后,another_owned_string 保持不变(注意没有 mut 限定符)。还有另一种变体 消耗 String 但不要求它是可变的。这是一个 implementation of the Add trait,左边是 String,右边是 &str

fn main() {
    let owned_string: String = "hello ".to_owned();
    let borrowed_string: &str = "world";
    
    let new_owned_string = owned_string + borrowed_string;
    println!("{}", new_owned_string);
}

请注意,在调用 + 后,owned_string 将无法再访问。

如果我们想生成一个新字符串,同时保持两个字符串不变怎么办?最简单的方法是使用 format!:

fn main() {
    let borrowed_string: &str = "hello ";
    let another_borrowed_string: &str = "world";
    
    let together = format!("{}{}", borrowed_string, another_borrowed_string);

    // After https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html
    // let together = format!("{borrowed_string}{another_borrowed_string}");

    println!("{}", together);
}

请注意,两个输入变量都是不可变的,因此我们知道它们没有被触及。如果我们想对 String 的任意组合做同样的事情,我们可以利用 String 也可以格式化的事实:

fn main() {
    let owned_string: String = "hello ".to_owned();
    let another_owned_string: String = "world".to_owned();
    
    let together = format!("{}{}", owned_string, another_owned_string);

    // After https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html
    // let together = format!("{owned_string}{another_owned_string}");
    println!("{}", together);
}

虽然您没有使用format!。您可以 clone one string 并将另一个字符串附加到新字符串:

fn main() {
    let owned_string: String = "hello ".to_owned();
    let borrowed_string: &str = "world";
    
    let together = owned_string.clone() + borrowed_string;
    println!("{}", together);
}

注意 - 我所做的所有类型说明都是多余的 - 编译器可以推断出所有类型。我添加它们只是为了让刚接触 Rust 的人清楚,因为我希望这个问题在那个群体中很受欢迎!

要将多个字符串连接成一个字符串,用另一个字符分隔,有几种方法。

我见过的最好的方法是在数组上使用 join 方法:

fn main() {
    let a = "Hello";
    let b = "world";
    let result = [a, b].join("\n");

    print!("{}", result);
}

根据您的用例,您可能还更喜欢更多控制:

fn main() {
    let a = "Hello";
    let b = "world";
    let result = format!("{}\n{}", a, b);

    print!("{}", result);
}

我看到了一些更多的手动方法,有些避免了这里那里的一两次分配。出于可读性目的,我发现以上两个就足够了。

我认为 concat 方法和 + 也应该在这里提到:

assert_eq!(
  ("My".to_owned() + " " + "string"),
  ["My", " ", "string"].concat()
);

还有 concat! 宏,但仅适用于文字:

let s = concat!("test", 10, 'b', true);
assert_eq!(s, "test10btrue");

在 Rust 中连接字符串的简单方法

Rust 中有多种方法可以连接字符串

第一种方法(使用concat!()):

fn main() {
    println!("{}", concat!("a", "b"))
}

以上代码的输出为:

ab


第二种方法(使用push_str()+运算符):

fn main() {
    let mut _a = "a".to_string();
    let _b = "b".to_string();
    let _c = "c".to_string();

    _a.push_str(&_b);

    println!("{}", _a);

    println!("{}", _a + &_c);
}

以上代码的输出为:

ab

abc


第三种方法(Using format!()):

fn main() {
    let mut _a = "a".to_string();
    let _b = "b".to_string();
    let _c = format!("{}{}", _a, _b);

    println!("{}", _c);
}

以上代码的输出为:

ab

查看并试验 Rust playground

通过字符串插值连接

更新:截至 2021 年 12 月 28 日,这在 Rust 1.58 Beta 中可用。您不再需要 Rust Nightly build 来进行字符串插值。 (为后代保留其余答案不变)。

2019 年 10 月 27 日发布的 RFC 2795: 建议支持隐式参数以执行许多人所知的“字符串插值”——一种将参数嵌入字符串以连接它们的方法。

RFC:https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html

最新的问题状态可以在这里找到: https://github.com/rust-lang/rust/issues/67984

在撰写本文时 (2020-9-24),我相信 Rust Nightly 构建中应该可以使用此功能。

这将允许您通过以下 shorthand 进行连接:

format_args!("hello {person}")

相当于:

format_args!("hello {person}", person=person)

还有“ifmt”crate,它提供了自己的字符串插值类型:

https://crates.io/crates/ifmt

默认情况下,Rust 中的所有内容都是关于 MemoryManage、Owenership 和 Move,因此我们通常看不到复制或深复制 如果您尝试连接字符串,则左侧应键入可增长且应为可变类型的字符串,右侧可以是普通字符串文字 a.k.a 类型字符串切片

    fn main (){
            let mut x = String::from("Hello"); // type String
            let y = "World" // type &str
            println!("data printing -------> {}",x+y);



}

来自 doc 的官方声明,这是指当您尝试使用 arthmatic + operator

从 Rust 1.58 开始,您还可以像这样连接两个或多个变量:format!("{a}{b}{c}")。这与 format!("{}{}{}", a, b, c) 基本相同,但更短且(可以说)更易于阅读。这些变量可以是 String&str(以及其他非字符串类型)。结果是String。 有关更多信息,请参阅 this

fn main() {
    let a = String::from("Name");
    let b = "Pkgamer";
    println!("{}",a+b)
}