Lesson 8 of 20
String Types
String Types in Rust
Rust has two main string types:
String — Owned, heap-allocated
String is a growable, heap-allocated UTF-8 string. You own it, and it is dropped when it goes out of scope:
let mut s = String::from("hello");
s.push_str(", world"); // mutate in place
s.push('!');
println!("{}", s); // hello, world!
&str — Borrowed string slice
&str is a reference to a sequence of UTF-8 bytes. String literals like "hello" are &str:
let s: &str = "hello"; // string literal — stored in binary
Converting Between Them
let owned: String = "hello".to_string();
let owned2: String = String::from("hello");
let borrowed: &str = &owned; // auto-deref
Useful String Methods
let s = "Hello, World!";
s.len() // 13 (bytes, not chars)
s.contains("World") // true
s.to_lowercase() // "hello, world!"
s.trim() // strips whitespace
s.split(", ") // iterator of parts
s.chars() // iterator of chars
format!
Build strings dynamically with format! — just like println! but returns a String:
let name = "Alice";
let greeting = format!("Hello, {}!", name);
Your Task
is_palindrome(s: &str) -> bool— returns true if the string reads the same forward and backward.count_vowels(s: &str) -> usize— counts vowels (a, e, i, o, u, case-insensitive).title_case(s: &str) -> String— capitalizes the first letter of each word.
Rust (Miri) loading...
Loading...
Click "Run" to execute your code.