rust 如何连接字符串?

mzaanser  于 2022-11-12  发布在  其他
关注(0)|答案(9)|浏览(178)

如何连接以下类型组合:

  • strstr
  • Stringstr
  • StringString
nhaq1z21

nhaq1z211#

连接字符串时,需要分配内存来存储结果,最简单的方法是从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可以被解引用为&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,但不要求它是可变的。这是Add特征的一个实现,它把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!,你可以克隆一个字符串,然后将另一个字符串追加到新字符串中:

fn main() {
    let owned_string: String = "hello ".to_owned();
    let borrowed_string: &str = "world";

    let together = owned_string.clone() + borrowed_string;
    println!("{}", together);
}

注意-我做的所有类型规范都是多余的-编译器可以推断出这里使用的所有类型。我添加它们只是为了让Rust的新手清楚,因为我希望这个问题在那个组中很受欢迎!

oalqel3c

oalqel3c2#

要将多个字符串连接成一个字符串,并用另一个字符分隔,有几种方法。
我见过的最好的方法是在数组上使用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);
}

还有一些我见过的手动方法,有些避免了一个或两个分配在这里和那里。为了可读性的目的,我发现以上两个是足够的。

pdsfdshx

pdsfdshx3#

在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

tyg4sfes

tyg4sfes4#

我认为这里还应该提到concat方法和+

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

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

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

at0kjp5o5#

通过字符串插值进行连接

更新:自2021年12月28日起,Rust 1.58测试版中提供了这个功能。你不再需要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构建中使用。
这将允许您通过以下简写进行连接:

format_args!("hello {person}")

它相当于:

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

还有一个“ifmt”框,它提供了自己的字符串插值:
https://crates.io/crates/ifmt

bybem2ql

bybem2ql6#

从Rust 1.58开始,您还可以连接两个或更多变量,如下所示:format!("{a}{b}{c}")。它基本上与format!("{}{}{}", a, b, c)相同,但更短一些,(可以说)更容易阅读。这些变量可以是String&str(也可以是其他非字符串类型)。结果是String。更多信息请参见this

kcugc4gi

kcugc4gi7#

串联两个String

fn concat_string(a: String, b: String) -> String {
    a + &b
}

串联两个&str

fn concat_str(a: &str, b: &str) -> String {
    a.to_string() + b
}
a1o7rhls

a1o7rhls8#

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

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

}

来自文档的官方声明,这是指当您尝试使用arthmatic +运算符时

am46iovg

am46iovg9#

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

相关问题