Introduction to Strings
Introduction to Strings
- What are Strings?
Strings are a sequence of Unicode characters. In Rust, a String is not null-terminated unlike strings in other programming languages. They can contain null characters.
Note: Have a look at the unicode characters
Types of Strings
- Strings are of two types: &str and String
- String Literal
(&str)
- String Literal
- A String literal has the following properties:
- Primitive type
- Immutable
- Fixed-length string stored somewhere in memory
- Value of string is known at compile time
Note: A String literal is also known as a String slice.
Create a String Literal
The following illustration shows how to create a primitive string:
output
String Object (String)
- A String object has the following properties:
- A string is encoded as a UTF-8 sequence
- Heap-allocated data structure
- The size of this string can be modified
- Not null-terminated
- Encode string values that are given at the run time
Create a String Object
There are many different ways to create and manipulate String objects. We will discuss two here.
Creating an Empty String Object
This method converts the empty String or a String literal to a String object using the .tostring
method.
The following illustration creates an empty String and then converts into the string object using the .to_string()
method.
Creating an Initialized String Object
This method creates a string with some default value passed as an argument to the from() method.
The following illustration creates a String literal and then converts it into the String object.
Note: len() is a built-in function used to find the length of a String literal and String object.
Last updated a year ago.