Rust handles string manipulation in a similar way to other programming languages, with a few key differences.
String literals are a special type of string that is statically allocated in the program's binary. This means that they cannot be changed after the program is compiled. String literals are denoted by using double quotes (") around the string, for example:
Rust
let hello_world = "Hello, world!";
String objects are a more flexible type of string that can be changed after the program is compiled. String objects are allocated in the heap, and they can grow or shrink as needed. String objects are created using the
String::from() method, for example:
Rust
let mut hello_world = String::from("Hello, world!");
hello_world.push_str(" This is Rust");
The string and &str types are two different ways to represent strings in Rust.
string is a growable, heap-allocated type, while &str is a reference to a fixed-size, statically allocated string.
In general, you should use string if you need to be able to change the string, and you should use
&str if you don't need to change the string.
Here is a table that summarizes the key differences between string and
&str:
Feature
string
&str
Memory allocation
Heap
Stack
Size
Can grow or shrink
Fixed
Mutability
Mutable
Immutable
Ownership
Owns the string data
Borrows the string data
Here are some examples of string manipulation in Rust:
Getting the length of a string:
Rust
let hello_world = "Hello, world!";
let length = hello_world.len();
Converting a string to uppercase:
Rust
let hello_world = "Hello, world!";
let uppercase_hello_world = hello_world.to_uppercase();
Splitting a string into a vector of words:
Rust
let hello_world = "Hello, world!";
let words = hello_world.split(" ").collect();
Replacing all occurrences of a substring with another substring:
Rust
let hello_world = "Hello, world!";
let new_hello_world = hello_world.replace("world", "Rust");
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Rust handles string manipulation in a similar way to other programming languages, with a few key differences.
") around the string, for example:Rust
String::from()method, for example:Rust
stringand&strThe
stringand&strtypes are two different ways to represent strings in Rust.stringis a growable, heap-allocated type, while&stris a reference to a fixed-size, statically allocated string.In general, you should use
stringif you need to be able to change the string, and you should use&strif you don't need to change the string.Here is a table that summarizes the key differences between
stringand&str:string&strHere are some examples of string manipulation in Rust:
Rust
Rust
Rust
Rust