Last active
January 23, 2018 03:23
-
-
Save nobleach/18bf8e63a999a9e2eaa934d0419476ef to your computer and use it in GitHub Desktop.
Reverse a string in Rust
This file contains hidden or 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
extern crate regex; | |
use regex::Regex; | |
fn main() { | |
let sentence = "We're all dorks!"; | |
println!("{}", reverse_string(sentence).to_string()); | |
} | |
fn reverse_string(string: &str) -> String { | |
let re = Regex::new(r"\b|\s").unwrap(); | |
let split = re.split(string); | |
let mut accumulator = Vec::new(); | |
for word in split { | |
accumulator.push(reverse_word(word)); | |
} | |
accumulator.join("") | |
} | |
fn reverse_word(word: &str) -> String { | |
word.chars().rev().collect::<String>() | |
} | |
#[test] | |
fn test_easy_string() { | |
assert_eq!(reverse_string("Hello World"), "olleH dlroW"); | |
} | |
#[test] | |
fn test_end_punctuation() { | |
assert_eq!(reverse_string("This is a string."), "sihT si a gnirts."); | |
} | |
#[test] | |
fn test_hardest() { | |
assert_eq!(reverse_string("Hey! That's a string with stuff in it. I wonder if I can handle that?"), "yeH! tahT's a gnirts htiw ffuts ni ti. I rednow fi I nac eldnah taht?") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment