如何在Rust中按char对字符串向量进行排序?

bnl4lu3b  于 2023-05-29  发布在  其他
关注(0)|答案(2)|浏览(159)

按字符对字符串向量进行排序的更惯用的方法是什么?
示例:
输入:
["3r", "2n", "2s", "7r", "1s", "1s", "6r", "1s", "1n", "1n", "5n", "9n", "3r"]
所需输出:
["1n", "1n", "2n", "5n", "9n, "3r", "3r", "6r", "7r", "1s", "1s", "1s", "2s"]
首先,它们需要在第二个字符上进行排序,以便将它们分组在一起,然后按第一个字符进行排序。
我用.filter.sort_by尝试了很多东西,但没有成功。

roqulrg3

roqulrg31#

你可以通过迭代器访问字符串中的字符:

#[test]
fn sort_by_second_char() {
    let mut input = [
        "3r", "2n", "2s", "7r", "1s", "1s", "6r", "1s", "1n", "1n", "5n", "9n", "3r",
    ];
    let output = [
        "1n", "1n", "2n", "5n", "9n", "3r", "3r", "6r", "7r", "1s", "1s", "1s", "2s",
    ];

    // this does not break even if the input string is of invalid format, if
    // you are sure they are valid you can unwrap.
    fn get_second_char(s: &&str) -> (Option<char>, Option<char>) {
        let mut chars = s.chars();
        let [num, char] = [chars.next(), chars.next()];
        (char, num)
    }

    input.sort_by_key(get_second_char);

    assert_eq!(input, output);
}

注意,如果元组的相应元素实现Ord,则元组实现Ord。如果它 Package 的类型实现Ordchar),则Option实现Ord

syqv5f0l

syqv5f0l2#

如果你的字符串总是两个字符长,并且你总是想先按第二个字符对它们进行排序,你可以使用.sort_by和一个比较器来反向查看字符串:

let mut input = vec!("3r", "2n", "2s", "7r", "1s", "1s", "6r", "1s", "1n", "1n", "5n", "9n", "3r");
input.sort_by(|a, b| a.chars().rev().cmp(b.chars().rev()));
let expected = vec!("1n", "1n", "2n", "5n", "9n", "3r", "3r", "6r", "7r", "1s", "1s", "1s", "2s");
assert!(input == expected);

相关问题