1
0
Fork 0
mirror of https://github.com/rust-lang/rustlings.git synced 2024-06-07 21:56:10 +02:00

Add some exercises about Strings and &strs!

This commit is contained in:
Carol (Nichols || Goulding) 2015-09-20 18:03:00 -04:00
parent ce3b710b13
commit 93869014f4
4 changed files with 114 additions and 0 deletions

File diff suppressed because one or more lines are too long

45
strings/strings1.rs Normal file
View File

@ -0,0 +1,45 @@
// Make me compile without changing the function signature! Scroll down for hints :)
fn main() {
let answer = current_favorite_color();
println!("My current favorite color is {}", answer);
}
fn current_favorite_color() -> String {
"blue"
}
// The `current_favorite_color` function is currently returning a string slice with the `'static`
// lifetime. We know this because the data of the string lives in our code itself -- it doesn't
// come from a file or user input or another program -- so it will live as long as our program
// lives. But it is still a string slice. There's one way to create a `String` by converting a
// string slice covered in the Strings chapter of the book, and another way that uses the `From`
// trait.

42
strings/strings2.rs Normal file
View File

@ -0,0 +1,42 @@
// Make me compile without changing the function signature! Scroll down for hints :)
fn main() {
let guess1 = "blue".to_string(); // Try not changing this line :)
let correct = guess_favorite_color(guess1);
if correct {
println!("You guessed correctly!");
} else {
println!("Nope, that's not it.");
}
}
fn guess_favorite_color(attempt: &str) -> bool {
attempt == "green"
}
// Yes, it would be really easy to fix this by just changing the value bound to `guess1` to be a
// string slice instead of a `String`, wouldn't it?? There is a way to add one character to line
// 5, though, that will coerce the `String` into a string slice.

18
strings/strings3.rs Normal file
View File

@ -0,0 +1,18 @@
// Ok, here are a bunch of values-- some are `Strings`, some are `&strs`. Your
// task is to call one of these two functions on each value depending on what
// you think each value is. That is, add either `string_slice` or `string`
// before the parentheses on each line. If you're right, it will compile!
fn string_slice(arg: &str) { println!("{}", arg); }
fn string(arg: String) { println!("{}", arg); }
fn main() {
("blue");
("red".to_string());
(String::from("hi"));
(format!("Interpolation {}", "Station"));
(&String::from("abc")[0..1]);
(" hello there ".trim());
("Happy Monday!".to_string().replace("Mon", "Tues"));
("mY sHiFt KeY iS sTiCkY".to_lowercase());
}