From 5c1e8698fa538a427d7fcb1ff45f3c434c22a83e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=9CM=C3=9C=C5=9E?= <96421894+Tahinli@users.noreply.github.com> Date: Sat, 20 Jul 2024 22:38:29 +0300 Subject: [PATCH] feat: :sparkles: strings --- 22-strings/Cargo.toml | 6 ++++++ 22-strings/src/main.rs | 49 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 22-strings/Cargo.toml create mode 100644 22-strings/src/main.rs diff --git a/22-strings/Cargo.toml b/22-strings/Cargo.toml new file mode 100644 index 0000000..636ed4f --- /dev/null +++ b/22-strings/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "strings" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/22-strings/src/main.rs b/22-strings/src/main.rs new file mode 100644 index 0000000..a9e8d83 --- /dev/null +++ b/22-strings/src/main.rs @@ -0,0 +1,49 @@ +fn main() { + println!("Hello, world!"); + + // This is how we can create a string. + let empty_string = String::new(); + println!("{}", empty_string); + + // This is how we can create string with initial value + let mut how_are_you = String::from("Hi"); + // This appends string to the string + how_are_you.push_str(", How are you "); + // This appends a char to the string + how_are_you.push('?'); + println!("{}", how_are_you); + + // to_string is also equivalent for String::from + let drink = "Drink".to_string(); + let water = "Water".to_string(); + let drink_water = drink + &water; + + println!("{}", drink_water); + + // This won't work since '+' operation takes ownership of first + // println!("{}", drink); + // But this works + println!("{}", water); + + let stay = "stay".to_string(); + let safe = "safe".to_string(); + + // This all going to work because format doesn't take ownerships + let stay_safe = format!("{}{}", stay, safe); + println!("{}", stay_safe); + println!("{}", stay); + println!("{}", safe); + + // This doesn't work because string indexes can't be reached like this. + // Because non ascii characters may take more than one slot. + // Rust prevents potential errors in the first place + // println!("{}", stay_safe[0]); + + for char in stay_safe.chars() { + println!("{}", char); + } + + for byte in stay_safe.bytes() { + println!("{}", byte); + } +}