Rust学习---示例1

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()
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值