Skip to content

Instantly share code, notes, and snippets.

@h4sh5
Created May 31, 2021 08:58
Show Gist options
  • Save h4sh5/63a86d031f521ee82eb2b096553bd339 to your computer and use it in GitHub Desktop.
Save h4sh5/63a86d031f521ee82eb2b096553bd339 to your computer and use it in GitHub Desktop.
function for trim spaces. good example for string iteration, borrowing, bytes datatype etc.
fn main() {
let test1 = "We need more space.";
assert_eq!(trim_spaces(test1), "We need more space.");
let test2 = String::from(" There's space in front.");
assert_eq!(trim_spaces(&test2), "There's space in front.");
let test3 = String::from("There's space to the rear. ");
assert_eq!(trim_spaces(&test3[..]), "There's space to the rear.");
let test4 = " We're surrounded by space! ";
assert_eq!(trim_spaces(test4), "We're surrounded by space!");
let test5 = " ";
assert_eq!(trim_spaces(test5), "");
let test6 = "";
assert_eq!(trim_spaces(test6), "");
let test7 = " 🚀 ";
assert_eq!(trim_spaces(test7), "🚀");
println!("Tests passed!");
}
/* YOUR CODE GOES HERE */
fn trim_spaces(orig: &str) -> &str {
// algo: iterate from beginning until the first non-space character
// then iterate from end until first non-space character
// to obtain start and end indexes to return
let mut start = 0;
let mut end = 0;
for (i, &c) in orig.as_bytes().iter().enumerate() {
if c != b' ' {
// found first non-space char
println!("found {} {:?}", i, c);
start = i;
break
}
}
println!("bytes len: {}", orig.len());
for (i, &c) in orig.as_bytes().iter().enumerate().rev() { // in reverse
println!("rev {} {}", i ,c);
if c != b' ' {
// found first non-space char
println!("found end {} {}", i, c);
end = i + 1;
break
}
}
&orig[start..end]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment