Advanced String Methods in Rust

Introduction

Hello! In this lesson, we will dive into some advanced string manipulation methods in Rust. Building on the previous knowledge of basic string operations, you will learn how to find substrings, check for the presence of a substring within another string, replace parts of a string, and transform strings using splitting and joining techniques.

Let's get started!

Finding a Substring

In Rust, you can use the string method .find() to locate the position of a substring within another string. This can be particularly useful when you need to determine whether a certain pattern exists in your text. The .find() method in Rust returns an Option<usize>, and it can yield two types of values:

  1. Some(index)
    • This variant signifies that the substring was found within the string.
    • index is the starting position (0-based index) of the first occurrence of the substring within the string.
  2. None
    • This variant indicates that the substring was not found within the string.

Here’s an example:

fn main() {
    let s = String::from("Hello, world!");
    match s.find("world") {
        Some(index) => println!("Found 'world' at index: {}", index),  
        None => println!("'world' not found")
    }
    // Prints: "Found 'world' at index: 7"
    
    match s.find("Rust") {
        Some(index) => println!("Found 'Rust' at index: {}", index),
        None => println!("'Rust' not found")
    }
    // Prints: 'Rust' not found
}

In this code:

  • s.find() will return either Some(index) or None
  • If the value is Some(index), execute the first arm of the match statement
  • If the value is None, execute the second arm of the match statement.

Checking for Substring Presence

Another common task is to check if a substring exists within a string using the .contains() method. It returns a boolean value, which you can use to conditionally execute parts of your code.

Consider this example:

fn main() {
    let s = String::from("Hello, world!");
    if s.contains("world") {
        println!("The string contains 'world'");  // Prints: "The string contains 'world'"
    } else {
        println!("The string does not contain 'world'");
    }
}

In this snippet:

  • We create a String variable s.
  • We use the .contains("world") method, which returns true if the substring is found, and false otherwise.
  • With an if statement, we print a corresponding message based on whether the substring is present.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal