Created
July 16, 2019 19:49
-
-
Save rust-play/715823a85842ad6d7b439241d8a50a6d to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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
fn reverse(input: &str) -> String { | |
let string = input.to_string(); | |
string | |
.split(' ') | |
.map(|word| { | |
if word.len() < 5 { | |
word.to_string() | |
} else { | |
word.chars().rev().collect() | |
} | |
}) | |
.collect::<Vec<_>>() | |
.join(" ") | |
} | |
fn reverse2(input: &str) -> String { | |
let mut output = input.as_bytes().to_vec(); | |
let len = output.len(); | |
let mut start; | |
let mut end = 0; | |
for i in 0..len-1 { | |
if output[i+1] == b' ' { | |
start = end; | |
end = i; | |
if (end - start) >= 5 { | |
println!("long"); | |
let word = &mut output[start..end]; | |
word.reverse(); | |
} | |
println!( | |
"{}", | |
String::from_utf8(output[start..end].to_vec()).unwrap() | |
); | |
} | |
} | |
String::from_utf8(output).unwrap() | |
} | |
fn main() { | |
println!("{}", reverse("Zhopa is a life worth living")); | |
println!("{}", reverse2("Zhopa is a life worth living")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment