Strings In Rust

Introduction

A string is a combination of characters in programming. It is a type of data we can use to represent textual information. We can use letters, numbers, symbols, and whitespace in a string. We frequently utilize strings to process text-based data, save user input, and display output to the user, among other things. Strings are commonly written in quotes in almost all programming languages, either single quotes ('hello') or double quotes ("hello").

We can perform different string operations to alter strings, including concatenation, substring extraction, and searching for particular patterns or characters within a string. Most programming languages have functions for manipulating strings that make these tasks easier. Now, let's see what is a string in Rust and how we use it.
Strings In Rust

What is a string in Rust?

A string is a sequence of Unicode characters encoded into UTF-8 bytes. The Unicode encoding provides efficient storage of strings. A string can be anything like words, sentences, etc. Strings are an important concept in computer programming as they are heavily used in programs that involves textual data.

In Rust, we can classify these strings into two types. They are

  • String Literal (&str)
  • String Object (String)

String Literals (&str) in Rust

A string literal is a slice of string that is a sequence of UTF-8 characters. They are used when the value of a string is known at the compile time. They are a set of characters that we hardcode to a variable. String literals are present in module std::str. In case we do not mention the type of string in our program, it will be considered as a string literal by default.

Syntax

let x:&str="string text";

In the above syntax, x is variable, &str is its type which is string literal. and string text is assigned to the variable x.

Example

fn main()
{
    let str = "Hello world";
    println!("value is {}",str);
}

Output

Istring in rust

In the above example, we have created a string literal named str and assigned it value. Here, we have not explicitly specified the type of variable as Rust will automatically infer it as a string literal as the default type is &str. In the next line, we print the string literal, which gives the output hello world.

String Object (String) in Rust

String object is present in Standard Library and defined as a public structure in the standard library pub struct String. The string size is not known at compile time as the string object is allocated in heap memory, and it is used to represent string values that are available at runtime.

To create a string object in Rust

Syntax

let str=String::from("String text");

It will create a string object named str and assign it a string.

Example

fn main()
{
    let str=String::from("String text");
    println!("This is string : {}",str);
}

Output

string in rust

In the above example, we have created a string object named str and assigned it some string. In the next line, we print the string object str.

To create an empty string in Rust

Syntax

let mut str=String::new();

It will create an empty string named str.

To push values into String in Rust

Syntax

string_variable_name.push_str("String value");

It will push the String value on the top of the string_variable_name string object.

Example

fn main()
{
    let mut str=String::new();
    str.push_str("New String");
    println!("This is string : {}",str);
}

Output

string in rust

In the above example, we have created a mutable string object named str and have not assigned any value. In the next line, we have pushed a string onto the string object str using the push_str() function. In the next line, we print the string object str.

To convert a String Literal to a String Object in Rust

Using the to_string () function, we can convert a string literal to a String object using the to_string() function.

Syntax

let x:&str="Rust";
x.to_string();

Example

fn main()
{
    let x:&str="Rust";
    x.to_string();
    println!("This is string : {}",x);
}

Output

string in rust

In the above example, we have created a string literal named x and assigned it a string literal value. In the next line, we have converted the string literal variable x into the string object using the function to_string(). In the next line, we print the string object x.

Important Note

We can not access string objects using an index like other programming languages. It will give an error like the one below.

string in rust

String Object Functions in Rust

There are plenty of functions using which we can manipulate the string objects. These functions not only simplify our work but also are easy to use. Following are the functions that can be used with string objects

Replace() function in Rust

The replace() function is used to replace all the matches of the pattern with the new string. It does not modify the original string but stores the modified string in a new string.

Syntax

let string2=string1.replace("old string", "new string");

Example

fn main()
{
    let str1=String::from("String text");
    let str2=String:;from("text","object");
    println!("This is string: : {}",str1);
    println!("This is string: : {}",str2);

}

Output

string in rust

In the above example, we have created a string object named str1 and assigned it some value. In the next line, we have created a string object named str2. We have used replace()  function to replace the string text with a string object. In the next line, we print str1; in the next line, we print str2.

Push() function in Rust

The push() function is used to push a character to the end of the string. It will append that character at the end of the string.

Syntax

string1.push('x');

Example

fn main()
{
    let str1=String::from("String text");
    str1.push('x');
    println!("This is string: : {}",str1);
}

Output

string in rust

In the above example, we have created a mutable string object named str1 and assigned it some string. In the next line, we push a character x on the string object str1. In the next line, we print the string object str1.

Len() function in Rust

The len() function is used to calculate the length of the given string. If you want to calculate the length of a string you can write the stringname.len(), and it will return the length. We can then store the length in another variable and print it.

Syntax

let length=str1.len();

Example

fn main()
{
    let str1=String::from("String text");
    let len=Str1.len();
    println!("This is string: : {} and its length is : {}",str1,len1);

}

Output

string in rust

In the above example, we created a string object str1 and assigned some values. In the next line, we calculated the length of str1 using the len() function. In the next line, we print the string object str1 with its length len.

Trim() function in Rust

The trim() function is used to remove the whitespace before and after the given string.

Syntax

let str2=str1.trim();

Example

fn main()
{
    let str1=String::from("    Rust  ");
    let len1=str1.len();
    let str2=str1.trim();
    let len2=str2.len();
    println!("str1 : {} and its length :{}",str1,len1);
    println!("str2 : {} and its length :{}",str2,len2);
}

Output

string in rust

In the above example, we have created a string object named str1 and assigned some value to it. In the next line, we created a variable named len1 and assigned it the length of str1 using the len() function. In the next line, we trim all the whitespace present in the string object str1 using the function trim() and stored it in another string object that we created named str2. In the next line, we calculated the length of string object str2 and assigned it a variable named len2. In the next line, we print str1 with its length len1. In the next line, we print str2 with its length len2.

Conclusion

In this article, we have learned all the important concepts of string in Rust programming language and discussed how we could use it in our program with code examples. We learned about two types of string in Rust, i.e., string literal and string object. We also discussed different functions that we can apply to the string object.

Frequently Asked Questions (FAQs)

Q1. Is Rust String a Collection?

A- In Rust, a String is considered a collection of characters. It is implemented as a growable, mutable sequence of Unicode code points with a length that can change as elements are added or removed.

Q2. Is Rust String immutable?

A- By default, Rust strings are immutable as they are considered string literal, but we can make them mutable using a string object instead of a string literal.

Q3. What is the difference between a String and a string literal in Rust?

A- String is a mutable, growable string-type object owned by the program, while a string literal is a fixed-size, immutable string compiled directly into the program's binary. String literals are of type &'static str.

Q4. How do I convert a String to a string literal or vice versa?

A- You can convert a String object to a string literal by using the as_str() method, which returns a reference to the string as a string slice (&str). You can convert a string literal to a String object by using the to_string() or into() method, which creates a new String with the same contents as the string literal.

Q5. How do I concatenate two or more strings in Rust?

A- You can use the + operator or the format!() macro to concatenate strings in Rust.

For example

let s = "hello".to_string() + " " + "world!";

Or,

let s = format!("{} {}", "hello", "world!");


Similar Articles