Rust, lesson 8
Rust has two main string types, and knowing which is which removes most early confusion.
String is an owned, growable buffer of UTF-8 text. You can push to it and change it.&str (a "string slice") is a borrowed view of some text owned by someone else: a
String, or a literal baked into your program like "hello".A good rule: functions that only read text take &str parameters. They then accept both
literals and borrowed Strings. Return a String when you build new text.
Splitting gives an iterator of pieces:
2 exercises to try what you just read.
&strformat! works like println! but returns a String instead of printing it. To glue
strings, + takes an owned String on the left and a &str on the right:
let full = first + " " + &last;.
A String stores UTF-8 bytes. Many characters take more than one byte, so s.len() counts
bytes, and Rust does not let you index a string with s[0]: a byte position might land in
the middle of a character. Instead you iterate:
A char is one Unicode scalar value. It has handy methods: c.is_alphabetic(),
c.is_ascii_digit(), c.is_whitespace(), c.to_ascii_uppercase(). Its to_uppercase()
returns an iterator (some characters become several in uppercase), which you can feed into a
string with collect or extend.
To take the first character safely: word.chars().next() returns an Option<char>, which is
None for an empty string.
Build up a result with a mut String and push / push_str, or collect an iterator of chars
straight into a String:
The |c| ... part is a closure, a small anonymous function. Here it decides which
characters to keep.
The second exercise is a small project using lessons 1 to 7: reading input, loops, decisions,
a helper function, a Vec, a HashMap and today's string tools. Plan it first: split the
text into words, clean each word, then compute one statistic at a time.
Read one line containing a full name (words separated by one or more spaces). Print the initials in uppercase, each followed by a dot, with no spaces.
Sample input:
Sample output:
Read all of the input (it may span several lines) and split it into words on whitespace. Clean each word by making it lowercase and keeping only alphabetic characters; skip words that become empty. Then print:
If there are no words, print only words: 0.
Sample input:
Sample output:
let greeting: &str = "hello"; // a literal is a &str
let mut owned: String = String::from("hi"); // or "hi".to_string()
owned.push_str(", there");
owned.push('!');
let view: &str = &owned; // borrow a String as &strlet s = " Hello, Rustacean! ";
s.trim(); // "Hello, Rustacean!"
s.to_uppercase(); // a new String
"seafood".contains("foo"); // true
"rustic".starts_with("rust"); // true
"chicken".find("ken"); // Some(4)
"a-b-c".replace("-", "+"); // "a+b+c"
"ab".repeat(3); // "ababab"for part in "a,b,c".split(',') { /* "a", "b", "c" */ }
let words: Vec<&str> = " two words ".split_whitespace().collect();
let joined = words.join("-"); // "two-words"let word = "café";
println!("{}", word.len()); // 5 bytes
println!("{}", word.chars().count()); // 4 characters
for c in word.chars() {
print!("{c} ");
}let only_letters: String = "a1b2c3".chars().filter(|c| c.is_alphabetic()).collect();
// "abc"ada king lovelaceA.K.L.words: <number of cleaned words>
unique: <number of different cleaned words>
longest: <the longest cleaned word (in characters); if several tie, the first one>
top: <the most frequent word; if several tie, the one that appeared first> (<count>)The cat sat. The CAT ran!
A dog? The end.words: 10
unique: 7
longest: the
top: the (3)