在开发程序的时候我们时常会需要判断某个字符串的开头或结尾是否符合某个字符串,例如判断网址是否以 http 或是 https 开头时,或是判断文件名称是否以 .jpg 或是 .png 结尾时。然而在上述提到的例子中,通信协定或是文件扩展名都是可忽略大小写的,Rust 编程语言虽然有提供 eq_ignore_ascii_case 方法,却没有提供 starts_with_ignore_ascii_case 和 ends_with_ignore_ascii_case 等方法,在判断上述例子时需要程序员自行先把字符串做转大写或是转小写的动作才能进行判断。
如以下程序,可以判断一个文件路径的扩展名是否为 png。
if path.to_lowercase().ends_with(".png") {
...
}
以上程序,因为我们不知道 path 的扩展名是 png、PNG,还是 PnG,因此只好先将其透过 to_lowercase 方法来转成小写,如此一来只要用 ends_with 来判断它是否以 .png 结尾就好。
然而,对字符串使用 to_lowercase 方法,会另外产生新的字符串出来,这会让程序内存用得更多,程序性能也会变得比较不好。
所以,比较好的作法是,先取得 path 的扩展名部份的字符串切片,再利用 Rust 编程语言的字符串内置的 eq_ignore_ascii_case 方法,来做判断。程序改写如下:
if path[(path.len() - ".png".len())..].eq_ignore_ascii_case(".png") {
...
}
这样写起来有点麻烦,而且还有可能因 path 本身没有到达 .png 的长度,而导致程序发生 panic,因此在将 path 转成更小范围的字符串切片前还需进行长度的检查。
str Utils
「str Utils」是笔者开发的套件,提供了一些特性,可以扩充有实作 AsRef<[u8]> 或是 AsRef<str> 特性的类型,使它们拥有更多的字符串相关的方法。
Crates.io
Cargo.toml
使用方法
文章一开始举的例子,可以用 EndsWithIgnoreAsciiCase 特性改写成以下程序:
use str_utils::EndsWithIgnoreAsciiCase;
...
if path.ends_with_ignore_ascii_case(".png") {
...
}
另外,由于我们可以确定输入至 ends_with_ignore_ascii_case 方法的字符串一定是小写,所以可以改用 ends_with_ignore_ascii_case_with_lowercase 方法以获得更好的性能。
use str_utils::EndsWithIgnoreAsciiCase;
...
if path.ends_with_ignore_ascii_case_with_lowercase(".png") {
...
}
当然这个套件的功能不只这些,再举几个用法:
use str_utils::*;
assert_eq!(true, "foobar".starts_with_ignore_ascii_case("FoO"));
assert_eq!(Some(1), "photo.jpg".ends_with_ignore_ascii_case_multiple(&[".png", ".jpg", ".gif"]));
assert_eq!(true, "http".eq_ignore_ascii_case_with_uppercase("HTTP")); // faster than `eq_ignore_ascii_case`
