Skip to content

Instantly share code, notes, and snippets.

@nobleach
Last active January 23, 2018 03:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nobleach/18bf8e63a999a9e2eaa934d0419476ef to your computer and use it in GitHub Desktop.
Save nobleach/18bf8e63a999a9e2eaa934d0419476ef to your computer and use it in GitHub Desktop.
Reverse a string in Rust
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