second exercise!

- create exercise string manipulator (shout out claude)
- finish hacky solution (it almost works)
This commit is contained in:
2026-01-15 09:10:06 +00:00
parent 6713144522
commit 0b910bf74d
3 changed files with 123 additions and 0 deletions

View File

@@ -0,0 +1,87 @@
use std::collections::HashMap;
fn main() {
let mut test = StringTool::new();
test.add_string("hello".to_string());
test.add_string("world".to_string());
test.add_string("rust programming".to_string());
println!("\nDEBUG: current values\n\t{:?}", test);
let word = "o".to_string();
let strings_with_word = test.contains_word(&word);
println!(
"DEBUG: string(s) with {word} are:\n\t{:?}",
strings_with_word
);
let longest = test.longest().unwrap_or("collection is empty!");
println!("{longest}");
test.to_uppercase_all();
println!("{:?}", test);
}
#[derive(Debug)]
struct StringTool {
collection: Vec<String>,
}
impl StringTool {
fn new() -> StringTool {
StringTool {
collection: Vec::new(),
}
}
fn add_string(&mut self, s: String) {
self.collection.push(s);
}
fn longest(&self) -> Option<&str> {
if self.collection.len() < 1 {
return None;
} else {
let mut longest_string = &self.collection[0];
let mut length = longest_string.len();
let mut count = 0;
for v in &self.collection {
if v.len() > length {
longest_string = v;
length = longest_string.len();
}
count += 1;
}
Some(longest_string.as_str())
}
}
fn to_uppercase_all(&mut self) {
for v in &mut self.collection {
*v = v.to_uppercase();
}
}
//TODO improve search
fn contains_word(&self, word: &str) -> Vec<&str> {
let collection = &self.collection;
let mut return_val: Vec<&str> = Vec::new();
//for strings in collection
for v in collection {
let words: Vec<_> = v.split_ascii_whitespace().collect();
//for words in string
for w in words {
// for characters in word
if w == word {
return_val.push(v);
}
}
}
return_val
}
}
//
// fn word_count(&self) -> HashMap<String, usize> {
// // counts total occurences of each word
// }