反转字符串-Reverse String
1. Readme
反向的字符串
反向的字符串
例如:
- input: “cool”
- output: “looc”
加分
用这个字符串:uüu
测试你的函数, 看会发生什么。试着写一个函数,这恰当地反转这个字符串。提示: {grapheme clusters
}
要拿到加分,需要测试加分项, 从最后一个测试中移除(#[ignore]
)标志),并运行下面测试命令:
$ cargo test --features grapheme
Source
Introductory challenge to reverse an input string https://medium.freecodecamp.org/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb
2. 开始你的表演
pub fn reverse(input: &str) -> String { unimplemented!("Write a function to reverse {}", input); }
3. 测试代码查看
# #![allow(unused_variables)] #fn main() { /// Tests for reverse-string /// /// Generated by [script][script] using [canonical data][canonical-data] /// /// [script]: https://github.com/exercism/rust/blob/master/bin/init_exercise.py /// [canonical-data]: https://raw.githubusercontent.com/exercism/problem-specifications/master/exercises/reverse-string/canonical_data.json /// Process a single test case for the property `reverse` fn process_reverse_case(input: &str, expected: &str) { assert_eq!(&reverse(input), expected) } #[test] /// empty string fn test_empty_string() { process_reverse_case("", ""); } #[test] //#[ignore] /// a word fn test_a_word() { process_reverse_case("robot", "tobor"); } #[test] //#[ignore] /// a capitalized word fn test_a_capitalized_word() { process_reverse_case("Ramen", "nemaR"); } #[test] //#[ignore] /// a sentence with punctuation fn test_a_sentence_with_punctuation() { process_reverse_case("I'm hungry!", "!yrgnuh m'I"); } #[test] //#[ignore] /// a palindrome fn test_a_palindrome() { process_reverse_case("racecar", "racecar"); } #[test] //#[ignore] /// wide characters fn test_wide_characters() { process_reverse_case("子猫", "猫子"); } #[test] //#[ignore] #[cfg(feature = "grapheme")] /// grapheme clusters fn test_grapheme_clusters() { process_reverse_case("uüu", "uüu"); } #}
4. 答案
# #![allow(unused_variables)] #fn main() { //! Example implementation for reverse-string pub fn reverse(input: &str) -> String { let mut output = String::with_capacity(input.len()); output.extend(input.chars().rev()); output } #}