Rust Strings


Rust Strings

In this tutorial, we will learn about strings in Rust. We will cover the basics of string manipulation, including creating, accessing, modifying, and performing operations on strings.


What is a String

A string in Rust is a sequence of characters. Rust has two main types of strings: String and &str. The String type is a growable, mutable, owned, UTF-8 encoded string, while &str is an immutable reference to a string slice.


Creating Strings

Strings can be created in Rust using String::from or using a string literal:

let str1 = String::from("Hello, world!");
let str2 = "Hello, world!";


Initializing Strings

  1. Create a string variable and initialize it with a value.
  2. Print the string variable using println!.

Rust Program

fn main() {
    let str = String::from("Hello, world!");
    println!("{}", str);
}

Output

Hello, world!


Accessing Characters in a String

  1. Create a string variable and initialize it with a value.
  2. Access and print individual characters using the chars method.

Rust Program

fn main() {
    let str = String::from("Hello");
    println!("{}", str.chars().nth(0).unwrap()); // Accessing using chars and nth method
    println!("{}", str.chars().nth(1).unwrap()); // using chars and nth method
}

Output

H
e


Modifying Strings

  1. Create a string variable and initialize it with a value.
  2. Strings in Rust are mutable, so you can modify them using various methods.
  3. Print the modified string.

Rust Program

fn main() {
    let mut str = String::from("Hello");
    str.replace_range(0..1, "J"); // Modifying a character
    str.push_str(" World!"); // Appending new characters
    println!("{}", str);
}

Output

Jello World!


String Concatenation

  1. Create two string variables and initialize them with values.
  2. Concatenate the strings using the + operator or the push_str method.
  3. Print the concatenated string.

Rust Program

fn main() {
    let str1 = String::from("Hello");
    let str2 = String::from(" World!");
    let str3 = str1 + &str2; // Concatenating strings
    println!("{}", str3);
}

Output

Hello World!


Finding Substrings

  1. Create a string variable and initialize it with a value.
  2. Use the contains method to find a substring.
  3. Print the existence of the substring.

Rust Program

fn main() {
    let str = String::from("Hello, world!");
    if str.contains("world") {
        println!("Substring found");
    } else {
        println!("Substring not found");
    }
}

Output

Substring found


String Length

  1. Create a string variable and initialize it with a value.
  2. Use the len method to get the length of the string.
  3. Print the length of the string.

Rust Program

fn main() {
    let str = String::from("Hello, world!");
    println!("Length of the string: {}", str.len());
}

Output

Length of the string: 13