OneBite.Dev - Coding blog in a bite size

Trim A String In Rust

Code snippet for how to Trim A String In Rust with sample and detail explanation

Rust is a multi-paradigm, high-level, general-purpose programming language that offers performance close to C and C++, but with readability and coding convenience similar to those offered by higher level languages. Today, we will be exploring a very common operation in most programming languages: how to trim a string in the Rust programming language.

Code Snippet: Trimming a String in Rust

Trimming a string in Rust can be achieved by invoking the .trim() function on the string you want to be trimmed. Below is a simple and straightforward code snippet demonstrating this:

fn main() {
    let my_string = "  Hello, World!  ";
    let trimmed_string = my_string.trim();

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

In the script above, we declared a string my_string with leading and trailing white spaces. Next, we invoke the .trim() function on my_string and store the result in trimmed_string. The println!() macro then prints the trimmed string to the console.

Code Explanation: Trimming a String in Rust

The .trim() function eliminates leading and trailing whitespace characters from the string on which it is applied. In our code, this operation happens with the line of code let trimmed_string = my_string.trim();.

The trim() function does not modify the original string (making it ‘immutable’), rather it creates a new one. This is why we had to store the result of the operation in a new variable, named trimmed_string.

Next, to print the value of trimmed_string, we used the println!() macro. This macro prints to the standard output. The string inside the macro {}, refers to the formatted string syntax in Rust, which will be replaced by the value we want to print.

Upon running the code, Hello, World! will be logged on the console, without the leading and trailing whitespaces, proving that our .trim() function worked correctly.

So this is how we can trim a string in Rust, using the .trim() function. It’s pretty simple and straightforward once you understand the concept of string immutability in Rust.

rust