Skip to content

Commit 50b3ac4

Browse files
added strings
1 parent c1f1cc3 commit 50b3ac4

1 file changed

Lines changed: 83 additions & 7 deletions

File tree

examples/09_strings.rs

Lines changed: 83 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ fn main(){
1818
// convert String --> &str
1919
let owned = String::from("hello");
2020
let borrowed : &str = &owned; // borrow it as &str
21-
prontln!("borrowed: {}", borrowed);
21+
println!("borrowed: {}", borrowed);
2222

2323
// PART 2: Building Strings
2424

@@ -29,21 +29,21 @@ fn main(){
2929

3030
// push --> append a single character
3131
s.push('!');
32-
println!("{}", S);
32+
println!("{}", s);
3333

3434
// + operator --> concatenates
3535
// NOTE: Consumes first string!!
3636
let s1 = String::from("Is this a real life ");
3737
let s2 = String::from("or just fantasy ");
3838

39-
let s3 = s1+s2; // s1 is MOVED here --> can't use s1 after this
39+
let s3 = s1 + &s2; // s1 is MOVED here --> can't use s1 after this
4040

4141
println!("{}", s3);
4242

4343
// format! macro --> joins w/o consuming (most flexible)
4444
let first = String::from("Caught in a landscape, ");
4545
let sec = String::from("no escape from reality");
46-
let combined = format!("{} {}!", first, second);
46+
let combined = format!("{} {}!", first, sec);
4747

4848
println!("{}", combined); //NOTE: first & sec are still valid -- format! borrows them
4949

@@ -73,15 +73,91 @@ fn main(){
7373

7474
// find --> returns the index of first match, or None
7575
match s.find("Rust") {
76-
Some(i) => println!("'Rust' found at index {}", i);
77-
None => println!("not found");
76+
Some(i) => println!("'Rust' found at index {}", i),
77+
None => println!("not found"),
7878
}
7979

8080
// PART 5 : Replacing
8181

8282
let s = String::from("I love Java and Java was my first programming language");
8383

8484
// replace --> replaces ALL occurences
85-
85+
let replaced = s.replace("Java", "Rust");
86+
println!("{}", replaced);
87+
88+
// replacen --> replaces only N occurrences
89+
let replaced_once = s.replacen("Java", "Rust", 1);
90+
println!("{}", replaced_once);
91+
92+
// PART 6 : Splitting --> most important for CLI tools
93+
94+
let sentence = "hello world foo bar";
95+
96+
let words: Vec<&str> = sentence.split(' ').collect();
97+
println!("split: {:?}", words);
98+
99+
// splitn --> split into AT MOST n parts
100+
// Very useful for parsing commands like "SET key value"
101+
let cmd = "SET my key some value with spaces";
102+
let parts: Vec<&str> = cmd.splitn(3, ' ').collect();
103+
println!("splitn(3): {:?}", parts);
104+
// ["SET", "my", "key some value with spaces"]
105+
// NOTICE: everything after the 2nd space stays together
106+
107+
// split and check first word
108+
let input = "echo hello world";
109+
let mut parts = input.splitn(2, ' ');
110+
let command = parts.next().unwrap_or("");
111+
let args = parts.next().unwrap_or("");
112+
113+
println!("command: '{}', args: '{}'", command, args);
114+
115+
// PART 7: Case Conversion
116+
117+
let s = "Hello Universe";
118+
println!("converted to lowercase: {}", s.to_lowercase());
119+
println!("converted to uppercase: {}", s.to_uppercase());
120+
121+
// PART 8: Parsing --> converting strings to other types
122+
let num: i32 = "42".parse().unwrap();
123+
println!("parsed i32: {}", num);
124+
125+
let float: f64 = "3.14".parse().unwrap();
126+
println!("parsed f64: {}", float);
127+
128+
// Handle parse failure safely
129+
match "abc".parse::<i32>() {
130+
Ok(n) => println!("parsed: {}", n),
131+
Err(e) => println!("parse failed: {}", e),
86132

133+
}
134+
135+
//number --> string
136+
let n = 42;
137+
let s = n.to_string();
138+
println!("number to string: {}", s);
139+
140+
// PART 9: Joining
141+
142+
let words = vec!["It's", "Rust Lang", "baby"];
143+
144+
// join --> connect items with a separator
145+
let sentence = words.join(" ");
146+
println!("{}", sentence);
147+
148+
let csv = words.join(",");
149+
println!("{}", csv);
150+
151+
// PART 10: Characters
152+
153+
let s = String::from("hello");
154+
for i in s.chars() {
155+
print!("{} ", i);
156+
}
157+
println!();
158+
159+
// Count characters
160+
let char_count = s.chars().count();
161+
println!("char count: {}", char_count);
162+
87163
}

0 commit comments

Comments
 (0)