在Rust中串联一个字符串的例子

977 阅读1分钟

在这个例子中,你会发现在Rust中串联字符串的多种方法,并有实例。

例如,你有两个用Rust声明的字符串。

    let first = "First";
    let second = "Second";

将两个字符串相加后,结果是First Second

如何在Rust中追加一个字符串

在Rust中,我们可以用多种方法来连接字符串

  • use join method

join 函数与分隔符字符串连接。分隔符可以是空格、制表符( )、我们的新行( )。\t``\n

fn main() {
    let first = "First";
    let second = "Second";
    let output = [first, second].join(" ");
    print!("{}", output);
}

输出

First Second
  • use format macro

format 函数宏用插值语法格式化字符串

它包含{} 语法,变量用逗号分隔。

变量被替换为{} ,并输出一个字符串。

fn main() {
    let first = "First";
    let second = "Second";
    let output = format!("{} {}", first, second);
    print!("{}", output);
}

输出

First Second
  • use concat macro concat 宏将多个字符串转换为一个字符串。它接受以逗号分隔的类型的字符串。&'static str
fn main() {
    let output = concat!("First", " ", "Second");
    print!("{}", output);
}

输出

First Second
  • push_str method push_str是一个用于将字符串追加到原始字符串的方法。 原始字符串被修改,并用mut 关键字声明。

下面是一个push_str追加字符串的示例程序

fn main() {
    let mut first = "First".to_string();
    let second = "Second".to_string();
    first.push_str(&second);
    println!("{}", first);
}

输出

FirstSecond
  • use + operator

  • 操作员将两个字符串连接起来,并将结果分配给一个新的变量。原始字符串没有被修改,所以不需要mut。

fn main() {
    let first = "First".to_string();
    let second = "Second".to_string();
    let result = first + &second;
    println!("{}", result);
}

输出

FirstSecond

结论

综上所述,通过实例学习了Rust中追加字符串的多种方法。