Working with Strings
Text is everywhere in programs — names, messages, stories, and more! In Rust, working with text (called strings) is super important. Let's learn how!
Two Kinds of Strings
Rust has two main string types:
&str(called a "string slice") — a piece of text that can't be changed. When you write"hello"in your code, that's a&str.String— a growable, changeable piece of text that lives on the heap.
Think of &str like a sign on a wall (you can read it but can't change it) and String like a whiteboard (you can write on it and erase it).
You can turn a &str into a String two ways:
String::from("hello")"hello".to_string()
Both do the same thing!
String Length and Checking Content
Use .len() to find out how many bytes a string has, and .contains() to check if a string includes some text:
Changing Case and Trimming
Rust gives you handy methods to change how text looks:
.to_uppercase()— makes everything SHOUTY.to_lowercase()— makes everything quiet.trim()— removes extra spaces from the beginning and end
Replacing Text
Use .replace() to swap one piece of text for another:
Combining Strings with format!()
The best way to combine strings in Rust is with format!(). It works just like println!() but gives you back a new String instead of printing:
You can use + to combine strings, but it's tricky because + takes ownership of the first string. format!() is easier and safer!
Working with Characters
A string is made up of individual characters. Use .chars() to get each character one at a time:
You can also grab a slice of a string using &s[start..end] (this works with byte positions):
This prints Rust — the characters from position 0 up to (but not including) position 4.
Summary
| Method | What it does |
|---|---|
String::from("hi") | Creates a String from text |
"hi".to_string() | Also creates a String from text |
.len() | Returns the length in bytes |
.contains("x") | Checks if a string contains text |
.to_uppercase() | Returns an ALL CAPS version |
.to_lowercase() | Returns an all lowercase version |
.trim() | Removes leading/trailing whitespace |
.replace("a", "b") | Replaces all "a" with "b" |
format!("{} {}", a, b) | Combines values into a new String |
.chars() | Iterates over each character |
&s[0..4] | Gets a slice of the string |
Now let's practice working with strings!