5 ways to concatenate string in Rust

Rust-Programs

In this article, we are going to learn about how to concatenate strings in the Rust language. We will learn multiple ways to do this.

5 ways to concatenate string in Rust


  • By using concat!() method.
  • By using using push_str() and + operator.
  • By using using + operator.
  • By using Using format!().
  • By using the join() method on an array.

1. By using concat!() method


In this program, we are concatenating string using the contact() function and finally printing the result.


fn main() {
    println!("{}", concat!("Hello", "World"));
	
	let sstrtest = concat!("Hello", 10, "Mike", true);
	println!("{}", sstrtest);
	
}

Output

rustc -o main main.rs
./main
HelloWorld
Hello10Miketrue

2. By using using push_str()


In this rust programming language program to concatenate string using the rust push_str() method and finally print the result using the print method.

fn main() {
    let mut _a = "Hello".to_string();
    let _b = "World".to_string();
    let _c = "Program".to_string();

    _a.push_str(&_b);

    println!("{}", _a);

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

Output

rustc -o main main.rs
./main
HelloWorld
HelloWorldProgram

3. By using + operator


In this rust programming language program to concatenate string using the plus(+) operator and finally print the result using the print method.

fn main() {
    let mut _a = "Hello".to_string();
    let _b = "World".to_string();
    let _c = "Program".to_string();

    _a.push_str(&_b);

    println!("{}", _a);

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

Output

rustc -o main main.rs
./main
HelloWorld
HelloWorldProgram

4.By using Using format!()


In this rust programming language program to concatenate string using the format! () method and finally print the result using the print method.

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

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

Output

rustc -o main main.rs
./main
HelloWorld

5.By using the join method on an array


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:

fn main() {
    let a = "Hello";
    let b = "World";
    let c = "Program";
    let result = [a, b,c].join(" ");

	let resultnxt = [a, b,c].join(",");
	
  print!("{}", result);
  print!("\n");
	print!("{}", resultnxt);
}

Output

rustc -o main main.rs
 ./main
Hello World Program
Hello,World,Program 

Summary

In this post we have learned 5 ways to concatenate string in Rust with the help of rust programs