Rust学习—示例1
描述:完成接受一个字符串参数的函数,并将该字符串中的每个字反转。字符串中的所有空格都应保留。
示例:
"This is an example!" ==> "sihT si na !elpmaxe"
"double spaces" ==> "elbuod secaps"
代码实现
// Rust tests
extern crate rand;
use self::rand::Rng;
#[test]
fn some_tests() {
assert_eq!(reverse_words("The quick brown fox jumps over the lazy dog."), "ehT kciuq nworb xof spmuj revo eht yzal .god");
assert_eq!(reverse_words("apple"), "elppa");
assert_eq!(reverse_words("a b c d"),"a b c d");
assert_eq!(reverse_words("double spaced words"), "elbuod decaps sdrow");
assert_eq!(reverse_words(""),"");
assert_eq!(reverse_words("ab ba cd"),"ba ab dc");
}
fn solution(str: &str) -> String {
let words = str.split(" ").collect::<Vec<_>>();
let mut res = "".to_string();
for w in words {
let mut x = w.to_string();
x += " ";
x = x.chars().rev().collect();
res.push_str(&x);
}
res[1..].to_string()
}
#[test]
fn random_tests() {
let words = ["Sam x abc", "harris yellow black", "patrick z uip", "Feenan evan mac", "Cole P hop", "Favuzzi greg", "david Lendieta cucker", "a b c d e f", "Kile clooney make me", "marky bark dark glock", " "];
for _ in 0..10 {
let test_string = words[rand::thread_rng().gen_range(0..words.len() - 1)];
println!("{}", test_string);
assert_eq!(reverse_words(&test_string), solution(&test_string));
}
}
fn reverse_words(str: &str) -> String {
// your code here
// "Test String".to_string()
str.split(" ")
.map(|x| x.chars()
.rev()
.collect::<String>())
.collect::<Vec<_>>()
.join(" ")
}
其他参考思路
fn reverse_words(str: &str) -> String {
let mut res = String::with_capacity(str.len());
for w in str.split(' ') {
res.extend(w.chars().rev());
if res.len() < str.len() {
res.push(' ')
}
}
res
}
fn reverse_words(str: &str) -> String {
let mut result = String::with_capacity(str.len());
let mut position = 0;
for (idx, chr) in str.chars().enumerate()
{
if chr.is_whitespace()
{
position = idx;
result.insert(position, chr);
position += 1;
}
else
{
result.insert(position, chr);
}
}
result
}
fn reverse_words(str: &str) -> String {
let mut reversed = String::new();
for word in str.split(" "){
reversed.push_str(&word.chars().rev().collect::<String>());
reversed.push_str(" ");
}
reversed[0..reversed.len()-1].to_string()
}
fn reverse_words(str: &str) -> String {
str.split(' ')
.into_iter()
.map(|word| word.chars().rev().collect::<String>())
.fold(String::new(), |r, c| r + c.as_str() + " ")
.trim_end()
.into()
}