Last active
August 29, 2015 14:17
-
-
Save gbersac/147e5f3340399fb3e454 to your computer and use it in GitHub Desktop.
Sub string for rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub fn sub_string(model: &String, begin: usize, len: usize) -> Option<String> | |
{ | |
let mut to_return = String::with_capacity(len); | |
let mut end = begin + len; | |
if begin > model.len(){ | |
return None; | |
} | |
if begin + len > model.len(){ | |
end = model.len() - begin; | |
} | |
Some(String::from_str(&(model[begin..end])) ) | |
} | |
#[test] | |
fn test_sub_string() | |
{ | |
let test1 = sub_string(&"aaabbbaaa".to_string(), 3, 3).unwrap(); | |
println!("test1: {}", test1); | |
assert_eq!(test1.as_slice(), "bbb"); | |
let test2 = sub_string(&"bbb".to_string(), 0, 3).unwrap(); | |
println!("test2: {}", test2); | |
assert_eq!(test2.as_slice(), "bbb"); | |
let test3 = sub_string(&"b".to_string(), 0, 3).unwrap(); | |
println!("test3: {}", test3); | |
assert_eq!(test3.as_slice(), "b"); | |
let test4 = sub_string(&"b".to_string(), 5, 3); | |
assert_eq!(test4, None); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment