Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

length
string
rust
communitycreator

How to get the length of a string in Rust

okwudili onyejiaku

Overview

The length of a string is the number of characters that make up that string. We can get the length of a string in Rust using the len() method.

Syntax

string.len()
Syntax for len method in Rust

Parameters

  • string: This is the string whose length we want to get.

Return value

The value returned is a number representing the length of the string specified.

Code

fn main() {
  // create some strings
  let str1 = "Edpresso";
  let str2 = "Educative";
  let str3 = "Rust";
  let str4 = "Educative is the best platform!";

  // print the length of the strings
  println!("The length of {} is {}", str1, str1.len());
  println!("The length of {} is {}", str2, str2.len());
  println!("The length of {} is {}", str3, str3.len());
  println!("The length of {} is {}", str4, str4.len());
}
Get the length of a string in Rust

Explanation

In the above code:

  • Lines 3–6: We create some string variables and initialize them.
  • Lines 9–12: We retrieve the length of each string with the len() method, and with the println!() method, we print the result to the console.

RELATED TAGS

length
string
rust
communitycreator
RELATED COURSES

View all Courses

Keep Exploring