You've already forked rust-tutor
114 lines
3.1 KiB
Rust
114 lines
3.1 KiB
Rust
fn main() {
|
|
let mut test = StringTool::new();
|
|
|
|
test.add_string("hello".to_string());
|
|
test.add_string("world".to_string());
|
|
test.add_string("learning rust is fun!".to_string());
|
|
test.add_string("rust programming".to_string());
|
|
println!("\nDEBUG: current values\n\t{:?}", test);
|
|
|
|
let word = "rust".to_string();
|
|
let strings_with_word = test.contains_word(&word);
|
|
println!(
|
|
"\nDEBUG: string(s) with \"{word}\" are:\n\t{:?}",
|
|
strings_with_word
|
|
);
|
|
|
|
let seq = "st".to_string();
|
|
let strings_with_seq = test.contains_seq(&seq);
|
|
println!(
|
|
"\nDEBUG: string(s) with \"{seq}\" are:\n\t{:?}",
|
|
strings_with_seq
|
|
);
|
|
|
|
let longest = test.longest().unwrap_or("collection is empty!");
|
|
println!("\nDEBUG: the longest string is: \"{longest}\"");
|
|
|
|
test.to_uppercase_all();
|
|
println!("\nDEBUG: everything uppercase \n\t{:?}", 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.is_empty() {
|
|
return None;
|
|
} else {
|
|
let mut longest_string = &self.collection[0];
|
|
let mut length = longest_string.len();
|
|
|
|
for v in &self.collection {
|
|
if v.len() > length {
|
|
longest_string = v;
|
|
length = longest_string.len();
|
|
}
|
|
}
|
|
Some(longest_string.as_str())
|
|
}
|
|
}
|
|
fn to_uppercase_all(&mut self) {
|
|
for v in &mut self.collection {
|
|
*v = v.to_uppercase();
|
|
}
|
|
}
|
|
|
|
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 {
|
|
if w == word {
|
|
return_val.push(v);
|
|
}
|
|
}
|
|
}
|
|
return_val
|
|
}
|
|
fn contains_seq(&self, seq: &str) -> Vec<&str> {
|
|
let collection = &self.collection;
|
|
let mut result: Vec<&str> = Vec::new();
|
|
let len_seq = seq.len();
|
|
let mut iterations = 0;
|
|
for v in collection {
|
|
let string_len = v.len() as usize;
|
|
if string_len % len_seq == 0 {
|
|
iterations = string_len - 1 - (string_len % len_seq);
|
|
} else {
|
|
iterations = string_len - (string_len % len_seq);
|
|
}
|
|
|
|
if len_seq > string_len {
|
|
return result;
|
|
} else {
|
|
for i in 0..iterations {
|
|
let slice = v.get(i..i + len_seq).unwrap();
|
|
if seq == slice {
|
|
result.push(&v);
|
|
break;
|
|
}
|
|
}
|
|
continue;
|
|
}
|
|
}
|
|
result
|
|
}
|
|
}
|