Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

string
empty
rust
communitycreator

How to check if a string is empty in Rust

okwudili onyejiaku

Overview

We can check if a string is empty in Rust by using the is_empty() method. A string is empty if it has no character.

Syntax

string.is_empty()
Syntax for is_empty() method

Parameters

string: This is the string we want to check to see if it is empty or not.

Return value

The value returned is a Boolean value. A true is returned if the string is actually empty. Otherwise, false is returned.

Code

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

  // print the length of the strings
  println!("{}", str1.is_empty());
  println!("{}", str2.is_empty());
  println!("{}", str3.is_empty());
  println!("{}", str4.is_empty());
}
Check if a String is empty in Rust

Explanation

In the above code:

  • Lines 3–5: We create some strings, some of which are empty and some of which are not.
  • Lines 9–12: We use the is_empty() method, and we check if each of the strings we created are empty. Then we print the result to the console.

RELATED TAGS

string
empty
rust
communitycreator
RELATED COURSES

View all Courses

Keep Exploring