String

A string in Rust is nothing but a data type which is used to represent a set of characters. String can be considered as a text, or a group of characters.

Example of strings:

  • Hello is a string.
  • Hello_Chercher.tech is a string
  • Hi_1 is also a string.

In Rust string can be classified into two different types:

  • String Literal which is denoted by &str.
  • String object which is denoted by String.

&str

String literal is used when the value of the string is known in the compile time. Using string literal we can assign the string directly to a string variable.

Syntax :

let variable_name:&str="value of the string";

A program to use string literal to print a string

fn main() {
   let country:&str="india";
   println!("My country is : {}", country);
}

Program Output :

rust-string-literals

Strings literals using static

This may be noted that, the strings literals are static by default, which means the value of the string will remain the same and valid for the entire program and can be used any where. But, we can specifically mention which strings has to be strictly static, by using the keyword static.

Syntax :

let variable_name: & 'static str = "String_name";

A program to store and print two static strings:

fn main() {
  let movie: & 'static str = "Robot";
  let director: & 'static str = "Shankar";
  println!("The movie {} is directed by {}", movie, director);
}

Program Output :

rust-string-static

String Object

String object is not present in the Rust Library and we must create it in order to use it. It can be defined as a structure in the Rust Standard Library as public and then can be used. The beauty of the string object is that, it is dynamic in nature and so can be used to represent values at the run time.

The string object are allocated in the heap

Syntax :

Creating an empty string: String:: new().

Creating an string, with a default value passed in the form() method: String::from().

A program to implement empty string and a non-empty string:

fn main(){
   let string1 = String::new();
   println!("The first string is empty, length is: {}",string1.len());
   let string2 = String::from("Chercher.tech");
   println!("The second string is not empty, length is: {}",string2.len());
}

In the above program, we have declared two string variable - string1 and string2. The first string is empty and is created by the string object String::new(). And the second string variable is assigned a valueChercher.tech.

Using the function len(), the length of the two strings are checked.

Program Output :

rust-string-object

Most important methods for Rust String Object

There are different methods which are used along with the strings objects. These methods are required to preform different operations with the String object. They are:

  • new() : This method creates an empty string.
  • to_string() : This method converts the any given value to a string.
  • len() : This method returns the length of a given string.
  • push() : This methods appends a character at the end of the string.
  • trim() : This method returns a string after removing the whilte spaces at the beginning and end of the string.
  • split_whitespace() : This method ....
Program Using new()

Syntax:

 let variable_name = String::new();

A program to create an empty string.

fn main(){
   let my_string = String::new();
   println!("This is an empty string and so, the length is: {}",my_string.len());
}

Program Output :

rust-string-empty

To assure that, an empty string has been created, we have checked the length of the string and found 0, which means that the string created is an empty string.

Program using to_string()

Syntax:

let variable_name = "text_to_convert".to_string();

A program to convert a text into string using the method to_string().

fn main(){
   let name = "Rahul".to_string();
   println!("{}",name);
}

Program Output :

rust-to-string

Program Using len()

Syntax :

String_name.len();

A program to find the length of a string

fn main() {
    let my_string = "hello";
    println!("{}", my_string);
    let length = my_string.len();
    println!("The length of the string is {}", length);
}

In the above program we have created string variabe called my_string and assigned it with a string value Hello. The variable length is a variable which stores the length of the string. let length = my_string.len();

Program Output :

rust-string-len

Program Using push()

Syntax :

String_name.push('character');

A program to attach a character at the end of a string

fn main() {
    let mut company = "Chercher.tec".to_string();
    company.push('h');
    println!("{}", company);
}

In the above program we have used the method push() to attach a character h at the end of the string chercher.tec.

Program Output :

rust-string-push

Program Using push_str()

Syntax :

String_name.push_str("string");

A program to append a part of a string to the end of a string.

fn main() {
  let mut company = "Chercher".to_string();
  company.push_str(".tech");
  println!("{}", company);
}

In the above program, we have declared a muted variable company and stored a string Chercher into it. Then, the push_str() function is used to append the string .tech at the end of the first string.

It may be noted that the variable storing the original string should be declared as muted, otherwise, the compiler will generate an error when we try to append another string at the end of the original string. This is required, because the string has been modified.

Program Output:

rust-string-push-str

Program Using trim()

Syntax :

string_name.trim()

A program to trim a string.

fn main() {
  let string_to_trim = "     chercher.tech     ";
  println!("The string with the end-spaces removed is {}", string_to_trim.trim());
}

In the above program, we have declared a variable string_to_trim which stores the string chercher.tech which contains spaces in the beginning and end of the string. Using the function trim(), the spaces can be removed.

Program Output :

rust-string-trim

The trim() method will only trim or eliminate the white spaces which are at the beggining and the end of the string, and will not remove the white spaces between the string.
Program using split()

Syntax :

for iterator_variable in String_name.split("Separator")

A program to separate values in a string in a comma (,)

fn main() {
  let subject = "physics,chemistry,maths";
  for value in subject.split(",") {
    println!("Subjects is {}", value);
  }
}

In the above program, we have declared a variable called subject and initialized it with a string, which contains three subjects each separate by a comma , (which is the separator in our case).

The split() function returns an iterator and thus we have used it with the help of the for loop- for value in subject.split(",") . Then we have simply printed the iterator_variable value to get the substrings.

We can use different separator instead of comma. You may try with a colon (:)

Program output :

rust-string-split

Program Using chars()

Syntax :

 for loop_variable in String_name.chars()

A program to print all the characters in a string separately.

fn main() {
    let country = "India".to_string();
    for character in country.chars() {
        println!("{}", character);
    }
}

In the above program, we have assigned a string INDIA, to the variable country. The method chars() returns an iterator, and so we use a for loop to print the string loop variable character, which is nothing but the single characters extarcted from the string INDIA.

Program Output :

rust-string-chars

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions