String Conversions and Methods

String Conversions and Methods

Hello! Welcome to this lesson on String Conversions and Methods in Rust. In the previous lesson, we delved into the fundamentals of Rust string methods and ownership, exploring how to handle strings efficiently. Today, we will build on that knowledge by learning how to convert data to and from strings, and how to manipulate strings using various methods. By the end of this lesson, you will have a solid understanding of these essential string operations in Rust.

Let's get started!

Introduction

Rust provides robust tools for string manipulation, making it easier to convert different data types to and from strings and apply various string methods, such as changing case, trimming spaces, and handling escape characters.

Let's see how Rust makes string conversions and manipulations straightforward and efficient.

String Conversions

Converting data to and from strings is a common necessity in programming, and Rust offers several utilities to perform these conversions seamlessly.

Here’s an example to demonstrate how to convert to and from string literals, String`, and numbers.

fn main() {
    let data = "initial contents";
    let s1 = data.to_string(); 
    println!("String: {}", s1);  // Prints: "String: initial contents"

    let s2 = String::from("Hello, world!");
    let s2_literal = s2.as_str();
    println!("{}", s2_literal);  // Prints: "Hello, world!"

    let num = 42;
    let num_str = num.to_string();
    println!("String: {}", num_str);  // Prints: "String: 42"

    let parsed_num: i32 = num_str.parse().unwrap();
    println!("Number: {}", parsed_num);  // Prints: "Number: 42"
}

In this snippet:

  • data.to_string() converts a string literal to a String type.
  • s2.as_str() converts a String to a string literal
  • num.to_string() converts an integer to a string.
  • num_str.parse() converts the string back into an integer. The method unwrap is used here to handle the potential error elegantly.

Changing Case

Changing the case of strings is a common requirement in text processing. Rust provides methods like to_lowercase and to_uppercase for this purpose. Using these methods does not transfer ownership.

Let's look at an example:

fn main() {
    let s = String::from("Hello, WORLD!");
    let lower_s = s.to_lowercase();
    println!("{}", lower_s);  // Prints: "hello, world!"

    let upper_s = lower_s.to_uppercase();
    println!("{}", upper_s);  // Prints: "HELLO, WORLD!"

    println!("s still has ownership of {}", s); // Prints: "s still has ownership of Hello, WORLD!"
}

In this code:

  • to_lowercase converts all characters in the string to lowercase.
  • to_uppercase converts all characters to uppercase.
  • Printing the value of s works because ownership has not been transfered
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