w3resource

Rust String: In-depth Guide with Examples


Understanding Rust Strings: Comprehensive Guide

Overview of Strings in Rust

Rust provides two primary types for handling text:

1. String: A growable, heap-allocated, UTF-8 encoded string.

2. str (string slice): An immutable reference to a sequence of UTF-8 characters, often used with &.

Rust ensures memory safety and performance while working with strings, making them an essential topic for developers.


Working with Rust Strings

Declaring a String

Strings in Rust can be created using the String::new or to_string methods.

Code:

// Create a new empty string
let mut my_string = String::new();  

// Add text to the string
my_string.push_str("Hello, Rust!");  

// Print the string
println!("{}", my_string);

Explanation:

    1. String::new() initializes an empty string.

    2. push_str appends text to the mutable string.

    3. The println! macro prints the string.


Converting &str to String

A &str can be easily converted into a String using the .to_string() method or String::from().

Code:

// Initialize a &str
let static_str = "Rust is awesome!";

// Convert to String
let dynamic_str = static_str.to_string();

// Print both
println!("Static: {}, Dynamic: {}", static_str, dynamic_str);

String Concatenation

Concatenate strings using the + operator or the format! macro.

Code:

// Declare strings
let str1 = String::from("Hello");
let str2 = " World";

// Concatenate with +
let greeting = str1 + str2;

// Concatenate with format!
let full_greeting = format!("{}{}", greeting, " in Rust");

// Print the result
println!("{}", full_greeting);

Common Operations on Strings

1. Length of a String

Code:

let text = String::from("Rustaceans");
println!("Length: {}", text.len());

2. Check if Empty

Code:

let empty_string = String::new();
println!("Is empty: {}", empty_string.is_empty());

3. Loop through Characters

Code:

let hello = String::from("Hello");
for c in hello.chars() {
    println!("{}", c);
}

4. Substring or Slicing

Code:

let phrase = String::from("Learning Rust");
let part = &phrase[0..8]; // Slicing first 8 characters
println!("{}", part);

5. Replace or Modify

Code:

let original = String::from("I love Java");
let updated = original.replace("Java", "Rust");
println!("{}", updated);

Key Points to Remember

  • Strings in Rust are UTF-8 encoded.
  • Use .push_str for appending and .push for single characters.
  • Use .trim() to remove leading and trailing whitespaces.
  • format! is often preferred for concatenation as it doesn’t take ownership of the arguments.

Rust Language Questions, Answers, and Code Snippets Collection.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/rust-tutorial/mastering-rust-strings.php