[][src]Function tao_of_rust::ch08::strings::practices

pub fn practices()

小例子

/* The program: You are given a text grid of size N by N.

Your program must choose words which are placed on the main and the secondary diagonals of the /// given grid.

The main diagonal is laid from the top-left to the bottom-right corner. The secondary diagonal is laid from the top-right to the bottom-left corner.​

INPUT: Line 1: An integer number N representing the grid size. Next N lines: N characters.

OUTPUT: Two words from the diagonals separated by a whitespace.

CONSTRAINTS: 0 < N ≤ 10 A grid contains only latin lowercase letters.

EXAMPLE: Input 4 mooa oano otio ioon

Output main anti

*/

解法1:

fn main(){
    let s = r"1234
                5678
                9876
                4321";
    let (mut x, mut y) = (0, 0);
    for (idx, val) in s.lines().enumerate() {
        let val = val.trim();
        let left = val.get(idx..idx+1)
                        .unwrap().parse::<u32>().unwrap();
       let right = val.get((3 - idx)..(3 - idx+1))
                         .unwrap().parse::<u32>().unwrap();
       x += left;
       y += right;
   }
   assert_eq!(38, x+y);
}Run

解法2:

fn main(){
    let s = r"mooa
              oano
              otio
              ioon";
    let v = s.split('\n').collect::<Vec<_>>();
    let mut s1 = String::new();
    let mut s2 = String::new();
    for (idx, val) in v.iter().enumerate() {
        let x = val.trim();
        let y = x.chars().collect::<Vec<_>>();
        println!("{:?}", y);
        s1.push(y[idx]);
        s2.push(y[3 - idx]);
    }
    s1.push(' ');
    println!("{:?}", s1 +  &s2);
}Run

解法3:

fn main(){
    let s = r"mooa
              oano
              otio
              ioon";
    let (mut s1, mut s2) = (String::with_capacity(4), String::with_capacity(4));
    for (idx, val) in s.lines().enumerate() {
        let val = val.trim();
        s1.push_str(val.get(idx..idx+1).unwrap());
        s2.push_str(val.get((3 - idx)..(3 - idx+1)).unwrap());
        // println!("s1 cap {:?}", s1.capacity());
        // println!("s2 cap {:?}", s2.capacity());
    }
    s1.push(' ');
    println!("{:?}", s1 +  &s2);
}Run