Rust 字元is_alphabetic、is_alphanumeric概述 - 判斷是否為字母
字母判斷
判斷字元是否為字母有幾個方法
分別是is_alphabetic和is_alphanumeric
差別在於一個是單純判斷字母
另一個是可以額外判斷樹字
文件這樣解釋
is_alphabetic[1]
pub fn is_alphabetic(self) -> bool
is_alphabetic可以判斷字母
舉個例子
fn main() {
let c_lowercase = 'a';
let c_uppercase = 'Z';
let c_digit = '5';
let c_punctuation = '!';
println!("Is alphabetic (lowercase): {}", c_lowercase.is_alphabetic());
println!("Is alphabetic (uppercase): {}", c_uppercase.is_alphabetic());
println!("Is alphabetic (digit): {}", c_digit.is_alphabetic());
println!("Is alphabetic (punctuation): {}", c_punctuation.is_alphabetic());
}
Is alphabetic (lowercase): true
Is alphabetic (uppercase): true
Is alphabetic (digit): false
Is alphabetic (punctuation): false
其中a和Z都是字母
因此輸出為true
但5和!不是
輸出false
is_alphanumeric[2]
pub fn is_alphanumeric(self) -> bool
is_alphanumeric可以判斷字母加上數字
也就是is_alphabetic和is_numeric[3]加起來
舉個例子
fn main() {
let c_lowercase = 'a';
let c_digit = '5';
let c_punctuation = '!';
println!("Is alphanumeric (lowercase): {}", c_lowercase.is_alphanumeric());
println!("Is alphanumeric (digit): {}", c_digit.is_alphanumeric());
println!("Is alphanumeric (punctuation): {}", c_punctuation.is_alphanumeric());
}
Is alphanumeric (lowercase): true
Is alphanumeric (digit): true
Is alphanumeric (punctuation): false
除了字母a會是true
數字5也會是true
驚嘆號則不是
其他語言
fn main() {
let chinese = '校';
let emoji = '💝';
println!("Is alphanumeric (校): {}", chinese.is_alphabetic());
println!("Is alphanumeric (校): {}", chinese.is_alphanumeric());
println!("Is alphanumeric (💝): {}", emoji.is_alphabetic());
println!("Is alphanumeric (💝): {}", emoji.is_alphanumeric());
}
Is alphanumeric (校): true
Is alphanumeric (校): true
Is alphanumeric (💝): false
Is alphanumeric (💝): false
中文字也算是字母的一種
因此也會顯示true
但emoji不是
參考資料
[1] https://doc.rust-lang.org/std/primitive.char.html#method.is_alphabetic
[2] https://doc.rust-lang.org/std/primitive.char.html#method.is_alphanumeric
[3] https://doc.rust-lang.org/std/primitive.char.html#method.is_numeric
0 comments:
張貼留言