You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Description: 'Strings in Rust are encodings of UTF-8 sequences, which can be created, manipulated and referenced.'
4
4
Subjects:
5
-
- 'Computer Science'
6
5
- 'Code Foundations'
6
+
- 'Computer Science'
7
7
Tags:
8
8
- 'Data Structures'
9
-
- 'Strings'
10
9
- 'Index'
10
+
- 'Strings'
11
+
- 'Unicode'
11
12
CatalogContent:
12
13
- 'learn-rust'
13
14
- 'paths/computer-science'
14
15
---
15
16
16
-
**Strings**in Rust diverge a little bit from conventional programming languages. The approach to string manipulation in Rust is influenced by its system-focused design. There are two types of strings that differ in various aspects such as modification, performance of operations and ownership rules.
17
+
In Rust, a **string**is essentially a sequence of Unicode characters encoded in UTF-8, which can be created, manipulated and referenced. For example, each character in the "Codecademy Rust Strings" string is a valid Unicode entity, i.e., "C", "o", "d", "e", "c", and so on.
17
18
18
-
Tackling data structures of variable size, such as strings, can get a bit tricky and Rust has its own spin on it. In Rust, a string is essentially a sequence of Unicode characters encoded in UTF-8. For example, each character in the "Codecademy Rust concept," string is a valid Unicode entity, i.e., "C," "o," "d," "e," "c," and so on.
19
+
Rust Strings diverge a little bit from conventional programming languages. The approach to string manipulation in Rust is influenced by its system-focused design. Though tackling them can get a bit tricky, they are essential for tasks such as reading user input, handling file paths, formatting output, managing configuration values, and communicating over networks.
19
20
20
-
## String types
21
+
## Types of Strings in Rust
21
22
22
-
In Rust, there are two main types related to strings, each serving a specific purpose.
23
+
In Rust, there are two types of strings that differ in various aspects such as modification, performance of operations, and [ownership](https://www.codecademy.com/resources/docs/rust/ownership) rules:
23
24
24
-
1.**`String`**
25
+
### 1. `String`
25
26
26
27
-**Description:** A heap-allocated, growable, and mutable string type.
27
28
-**Usage:** Used when dynamic string manipulation and ownership transfer are required.
@@ -30,91 +31,211 @@ In Rust, there are two main types related to strings, each serving a specific pu
-**Description:** A reference to a sequence of UTF-8 bytes, often used as a view into a `String` or a string
36
-
literal.
36
+
-**Description:** A reference to a sequence of UTF-8 bytes, often used as a view into a `String` or a string literal.
37
37
-**Usage:** Commonly used for string references without ownership or when dealing with parts of a string.
38
38
39
39
```rust
40
40
letstring_literal:&str="Hello, Rust!";
41
41
```
42
42
43
-
> **Note:** These string types cover various scenarios, from dynamic and mutable strings `String` to static and immutable string slices `&str`. The type of string should be chosen depending on the specific requirements and the characteristics of the data being manipulated.
43
+
> **Note:** These string types cover various scenarios, from dynamic and mutable strings (`String`) to static and immutable string slices (`&str`). The string type should be chosen depending on the specific requirements and the characteristics of the data being manipulated.
44
+
45
+
## Creating Strings in Rust
46
+
47
+
There are different ways to create a string in Rust:
48
+
49
+
### 1. Using `String::from()`
50
+
51
+
This example creates a string using `String::from()` in Rust:
44
52
45
-
## Creating Strings
53
+
```rust
54
+
letstr=String::from("Hello");
55
+
```
46
56
47
-
Here is an example of creating a string using `String::new()`:
57
+
### 2. Using `String::new()`
58
+
59
+
This example creates a string using `String::new()` in Rust:
48
60
49
61
```rust
50
62
letmutempty_string=String::new();
63
+
empty_string.push_str("Hello");
51
64
```
52
65
53
-
## String Manipulation
66
+
`String::new()` only allows us to create an empty string. After creating it, a value can be assigned to it using the `.push_str()` method.
54
67
55
-
### Concatenation
68
+
##Concatenating Strings in Rust
56
69
57
-
In Rust, there are multiple ways to concatenate strings. Here is a list of concatenation operators including examples:
70
+
There are several ways to concatenate strings in Rust:
58
71
59
-
**`+` Operator:**
72
+
### `+` Operator
60
73
61
-
-**Usage:**Concatenating two strings.
74
+
-**Usage:**Concatenates two strings.
62
75
-**Ownership:** Consumes the left operand.
63
-
-**Borrowing:** To concatenate with a borrowed string (sliced out of another string using `&str`), it is necessary to explicitly borrow it using the `&` operator.
76
+
-**Borrowing:** To concatenate with a borrowed string (sliced out of another string using `&str`), it is necessary to explicitly borrow it using the `&`[operator](https://www.codecademy.com/resources/docs/rust/operators).
64
77
65
78
```rust
66
-
lethello=String::from("Hello, ");
67
-
letworld=String::from("World!");
68
-
lethello_world=hello+&world; // Ownership of 'hello' is moved, 'world' is borrowed
79
+
fnmain() {
80
+
lethello=String::from("Hello, ");
81
+
letworld=String::from("World!");
82
+
83
+
lethello_world=hello+&world; // Ownership of 'hello' is moved, 'world' is borrowed
84
+
85
+
println!("{}", hello_world);
86
+
}
87
+
```
88
+
89
+
Here is the output:
90
+
91
+
```shell
92
+
Hello, World!
69
93
```
70
94
71
-
**`+=` Operator:**
95
+
### `+=` Operator
72
96
73
-
-**Usage:**In-place concatenation operation.
97
+
-**Usage:**Concatenates two strings in-place.
74
98
-**Ownership:** Consumes the existing string on the left operand and appends to it.
75
99
-**Borrowing:** It works directly with the mutable reference of the left operand, but the ownership of the left operand is transferred to the result.
76
100
77
101
```rust
78
-
letmuthello=String::from("Hello, ");
79
-
letworld=String::from("World!");
80
-
hello+=&world; // Appends 'World!' to the existing 'Hello, '
102
+
fnmain() {
103
+
letmuthello=String::from("Hello, ");
104
+
letworld=String::from("World!");
105
+
106
+
hello+=&world; // Appends 'World!' to the existing 'Hello, '
107
+
108
+
println!("{}", hello);
109
+
```
110
+
111
+
Here is the output:
112
+
113
+
```shell
114
+
Hello, World!
81
115
```
82
116
83
-
**`format!` Macro:**
117
+
### `format!` Macro
84
118
85
119
-**Usage:** Creates a new string by formatting text, allowing string interpolation.
86
-
-**Ownership:** It does not involve ownership transfer and is a convenient way to create strings without borrowing
87
-
or ownership concerns.
120
+
-**Ownership:** It does not involve ownership transfer and is a convenient way to create strings without borrowing or ownership concerns.
88
121
89
122
```rust
90
-
lethello=String::from("Hello, ");
91
-
letworld=String::from("World!");
92
-
lethello_world=format!("{}{}", hello, world); // Creates a new string without ownership issues
123
+
fnmain() {
124
+
lethello=String::from("Hello, ");
125
+
letworld=String::from("World!");
126
+
127
+
lethello_world=format!("{}{}", hello, world); // Creates a new string without ownership issues
128
+
129
+
println!("{}", hello_world);
130
+
}
93
131
```
94
132
95
-
> **Note:** When working with strings in Rust, it's crucial to be mindful of ownership and borrowing semantics, especially when using operators like `+`. The operator `+`is used to create a new string while `+=` is used to modify an existing string in place. To concatenate strings with interpolation the `format!` macro provides a flexible and ownership-friendly way.
133
+
Here is the output:
96
134
97
-
### Slicing & Appending with `push_str` and `push`
135
+
```shell
136
+
Hello, World!
137
+
```
138
+
139
+
> **Note:** When working with strings in Rust, it's crucial to be mindful of ownership and borrowing semantics, especially when using operators like `+`. The operator `+` is used to create a new string while `+=` is used to modify an existing string in-place. To concatenate strings with interpolation, the `format!` macro provides a flexible and ownership-friendly way.
140
+
141
+
## Slicing and Appending Strings in Rust
142
+
143
+
In this example, the `.push_str()` method is used to append a string slice to the existing string `message`, whereas the `.push()` method is used to add the character `!` to the end of the concatenated string:
98
144
99
145
```rust
100
-
letmutmessage=String::from("Rust");
101
-
message.push_str(" Programming");
102
-
message.push('!');
103
-
letpart_of_message=&message[0..5];
146
+
fnmain() {
147
+
letmutmessage=String::from("Rust");
148
+
149
+
message.push_str(" Programming");
150
+
message.push('!');
151
+
152
+
println!("{}", message);
153
+
}
104
154
```
105
155
106
-
In the example above, `push_str` is used to append a string slice to the existing string `message`, and `push` is used to add the character `!` to the end of the concatenated string.
156
+
Here is the output:
157
+
158
+
```shell
159
+
Rust Programming!
160
+
```
107
161
108
162
## Referencing Strings
109
163
110
-
To reference parts of a string without ownership `&str`can be used as follows:
164
+
This example demonstrates the usage of `&str`to reference parts of a string without ownership:
111
165
112
166
```rust
113
-
letfull_string=String::from("Hello, World!");
114
-
letslice=&full_string[0..5];
167
+
fnmain() {
168
+
letfull_string=String::from("Hello, World!");
169
+
170
+
letslice=&full_string[0..5];
171
+
172
+
println!("{}", slice);
173
+
}
174
+
```
175
+
176
+
Here is the output:
177
+
178
+
```shell
179
+
Hello
115
180
```
116
181
117
182
Here, `&full_string[0..5]` creates a reference to the first five characters of `full_string`.
118
183
119
-
A certain familiarity with the described methods and operators as well as the concept of string slices is crucial to
120
-
work efficiently with and fully grasp the syntax of Rust strings.
184
+
## Iterating over Strings in Rust
185
+
186
+
The `.chars()` method can be used to return an iterator of characters in a string, which can then be looped over:
187
+
188
+
```rust
189
+
fnmain() {
190
+
letstr=String::from("Rust");
191
+
192
+
forcharinstr.chars() {
193
+
println!("{}", char);
194
+
}
195
+
}
196
+
```
197
+
198
+
Here is the output:
199
+
200
+
```shell
201
+
R
202
+
u
203
+
s
204
+
t
205
+
```
206
+
207
+
## Frequently Asked Questions
208
+
209
+
### 1. How do I convert between `String` and `&str`?
210
+
211
+
`String` to `&str`: Use `.as_str()` or dereference (`&s`).
212
+
213
+
```rust
214
+
lets=String::from("Hello");
215
+
216
+
// Method 1: Using .as_str()
217
+
letslice1:&str=s.as_str();
218
+
219
+
// Method 2: Using dereferencing
220
+
letslice2:&str=&s;
221
+
```
222
+
223
+
`&str` to `String`: Use `.to_string()` or `String::from()`.
224
+
225
+
```rust
226
+
letslice="Hello";
227
+
228
+
// Method 1: Using .to_string()
229
+
lets1=slice.to_string();
230
+
231
+
// Method 2: Using String::from()
232
+
lets2=String::from(slice);
233
+
```
234
+
235
+
### 2. Why does Rust have 2 string types?
236
+
237
+
Rust separates strings into `String` and `&str` to balance performance and flexibility. `&str` is lightweight and fast, perfect for reading or referencing text, while `String` is ideal for ownership and mutation. This separation ensures memory safety and efficient handling of text data.
238
+
239
+
### 3. What is the difference between Rust string and C string?
240
+
241
+
Rust strings are safe and UTF-8 encoded, while [C strings](https://www.codecademy.com/resources/docs/c/strings) (`char*`) are null-terminated and unsafe. Rust avoids common C string pitfalls like buffer overflows by enforcing strict memory and type safety, at the cost of some complexity.
0 commit comments