Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

rust
communitycreator

What is the string.trim() method in Rust?

okwudili onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

In Rust, we can use the trim() method of a string to remove the whitespace characters around that string. This method removes the leading and trailing whitespace characters of a given string.

Syntax

This is the syntax of the trim() method:

string.trim()
Syntax of the trim() method of a string in Rust

Parameter value

string: This is the string we want to trim to remove its leading and trailing whitespace characters.

Example

Let’s look at the code example given below:

fn main() {
// create some strings
let string1 = " Welcome to Edpresso ";
let string2 = "Educative is the best! ";
let string3 = " Rust is very interesting!";
// trim the strings
let trim1 = string1.trim();
let trim2 = string2.trim();
let trim3 = string3.trim();
// print the trims
println!("The string before trim is '{}' and length is {}", string1, string1.len());
println!("The string when trimmed is '{}' and length is {}", trim1, trim1.len());
println!("\nThe string before trim is '{}' and length is {}", string2, string2.len());
println!("The string when trimmed is '{}' and length is {}", trim2, trim2.len());
println!("\nThe string before trim is '{}' and length is {}", string3, string3.len());
println!("The string when trimmed is '{}' and length is {}", trim3, trim3.len());
}
Trim a string in Rust with the trim() method

Explanation

  • Lines 3–5: We create some strings.
  • Lines 8–9: We trim the strings and save the results.
  • Lines 13–20: We print the results to the console.

RELATED TAGS

rust
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring