string 如何连接字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30154541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I concatenate strings?
提问by jsalter
How do I concatenate the following combinations of types:
如何连接以下类型的组合:
str
andstr
String
andstr
String
andString
str
和str
String
和str
String
和String
回答by Shepmaster
When you concatenate strings, you need to allocate memory to store the result. The easiest to start with is String
and &str
:
连接字符串时,需要分配内存来存储结果。最简单的开始是String
and &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);
}
Here, we have an owned string that we can mutate. This is efficient as it potentially allows us to reuse the memory allocation. There's a similar case for String
and String
, as &String
can be dereferenced as &str
.
在这里,我们有一个可以改变的拥有的字符串。这是有效的,因为它可能允许我们重用内存分配。还有一个类似的案例String
和String
作为&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);
}
After this, another_owned_string
is untouched (note no mut
qualifier). There's another variant that consumesthe String
but doesn't require it to be mutable. This is an implementation of the Add
traitthat takes a String
as the left-hand side and a &str
as the right-hand side:
在此之后,another_owned_string
保持不变(注意没有mut
限定符)。还有另一个变种消耗的String
,但并不要求它是可变的。这是trait 的一个实现Add
,将 aString
作为左侧,a&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);
}
Note that owned_string
is no longer accessible after the call to +
.
请注意,owned_string
在调用 后不再可访问+
。
What if we wanted to produce a new string, leaving both untouched? The simplest way is to use format!
:
如果我们想产生一个新的字符串,同时保持两个不变怎么办?最简单的方法是使用format!
:
fn main() {
let borrowed_string: &str = "hello ";
let another_borrowed_string: &str = "world";
let together = format!("{}{}", borrowed_string, another_borrowed_string);
println!("{}", together);
}
Note that both input variables are immutable, so we know that they aren't touched. If we wanted to do the same thing for any combination of String
, we can use the fact that String
also can be formatted:
请注意,两个输入变量都是不可变的,因此我们知道它们不会被触及。如果我们想对 的任何组合做同样的事情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);
println!("{}", together);
}
You don't haveto use format!
though. You can clone one stringand append the other string to the new string:
你不具备使用format!
虽然。您可以克隆一个字符串并将另一个字符串附加到新字符串:
fn main() {
let owned_string: String = "hello ".to_owned();
let borrowed_string: &str = "world";
let together = owned_string.clone() + borrowed_string;
println!("{}", together);
}
Note- all of the type specification I did is redundant - the compiler can infer all the types in play here. I added them simply to be clear to people new to Rust, as I expect this question to be popular with that group!
注意- 我所做的所有类型规范都是多余的 - 编译器可以在这里推断出所有类型。我添加它们只是为了让 Rust 的新手清楚,因为我希望这个问题在那个群体中很受欢迎!
回答by Simon Whitehead
To concatenate multiple strings into a single string, separated by another character, there are a couple of ways.
要将多个字符串连接成一个字符串,由另一个字符分隔,有几种方法。
The nicest I have seen is using the join
method on an array:
我见过的最好的join
方法是在数组上使用该方法:
fn main() {
let a = "Hello";
let b = "world";
let result = [a, b].join("\n");
print!("{}", result);
}
Depending on your use case you might also prefer more control:
根据您的用例,您可能还喜欢更多控制:
fn main() {
let a = "Hello";
let b = "world";
let result = format!("{}\n{}", a, b);
print!("{}", result);
}
There are some more manual ways I have seen, some avoiding one or two allocations here and there. For readability purposes I find the above two to be sufficient.
我见过一些更多的手动方式,有些避免在这里和那里进行一两个分配。出于可读性目的,我发现以上两个就足够了。
回答by suside
I think that concat
method and +
should be mentioned here as well:
我认为这种concat
方法也+
应该在这里提到:
assert_eq!(
("My".to_owned() + " " + "string"),
["My", " ", "string"].concat()
);
and there is also concat!
macro but only for literals:
还有concat!
宏,但仅适用于文字:
let s = concat!("test", 10, 'b', true);
assert_eq!(s, "test10btrue");
回答by ASHWIN RAJEEV
Simple ways to concatenate strings in RUST
在 RUST 中连接字符串的简单方法
There are various methods available in RUST to concatenate strings
RUST 中有多种方法可以连接字符串
First method (Using concat!()
):
第一种方法(使用concat!()
):
fn main() {
println!("{}", concat!("a", "b"))
}
The output of the above code is :
上面代码的输出是:
ab
AB
Second method (using push_str()
and +
operator):
第二种方法(使用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 + &_b);
}
The output of the above code is:
上面代码的输出是:
ab
abc
AB
美国广播公司
Third method (Using format!()
):
第三种方法(Using format!()
):
fn main() {
let mut _a = "a".to_string();
let _b = "b".to_string();
let _c = format!("{}{}", _a, _b);
println!("{}", _c);
}
The output of the above code is :
上面代码的输出是:
ab
AB
check it out and experiment with Rust play ground
检查一下并尝试Rust 游乐场