在开发程序时,常会需要将含有数字的字符串(例如:图片1,图片2,第1章,第2章)进行排序。编程语言通常会内置字符串排序功能,但是在排序字符串的时候大多会发生一个问题,那就是它们会「排错」字符串内的数字。举个例子,若要排序屏幕截屏文件的文件名,分别有 shot-2, shot-1 和 shot-11 这三张截屏,则文件名的正确排序的结果应为 shot-1, shot-2, shot-11,但许多编程语言只会按照字符串的辞典顺序,将文件名排成 shot-1, shot-11, shot-2 这样不直觉的结果,就连 Rust 编程语言也不例外。所以如果要让 Rust 编程语言正确排序含有数字的字符串,该怎么做呢?
Alphanumeric Sort
「Alphanumeric Sort」是笔者开发的套件,可以正确比较包含数字的字符串的顺序,并支持字符串数组和 Path 结构实体数组的排序。
Crates.io
Cargo.toml
alphanumeric-sort = "*"
使用方法
若要比较两个字符串的顺序,可以使用 compare_str 函数。
use std::cmp::Ordering;
assert_eq!(Ordering::Greater, alphanumeric_sort::compare_str("abc3210", "abc321"));
若要排序字符串数组(切片),可以使用 sort_str_slice 函数。
let mut names = ["shot-2", "shot-1", "shot-11"];
alphanumeric_sort::sort_str_slice(&mut names);
assert_eq!(["shot-1", "shot-2", "shot-11"], names);
若要排序 Path 结构实体数组(切片),可以使用 sort_path_slice 函数。
use std::path::Path;
let mut paths = [Path::new("shot-2"), Path::new("shot-1"), Path::new("shot-11")];
alphanumeric_sort::sort_path_slice(&mut paths);
assert_eq!([Path::new("shot-1"), Path::new("shot-2"), Path::new("shot-11")], paths);
另外还有 sort_os_str_slice 和 sort_c_str_slice 函数可以使用。
