Rust 如何将i32转换为表示ASCII字符的字符串
这个周末我在Rust做一个项目,我需要将i32转换成ASCII字符,并将其用作字符代码。到目前为止,我所拥有的只是一个巨大的Rust 如何将i32转换为表示ASCII字符的字符串,rust,ascii,Rust,Ascii,这个周末我在Rust做一个项目,我需要将i32转换成ASCII字符,并将其用作字符代码。到目前为止,我所拥有的只是一个巨大的匹配,我将它隐藏在一个文件的末尾。不幸的是,std::ascii不支持此转换。目前,我只是在寻找一种不那么荒谬/更像生锈(?)的方法来实现这一点 fn to_ascii(i: &i32) -> String { let a = match *i { 0 => "NUL", 1 => "SOH",
匹配
,我将它隐藏在一个文件的末尾。不幸的是,std::ascii
不支持此转换。目前,我只是在寻找一种不那么荒谬/更像生锈(?)的方法来实现这一点
fn to_ascii(i: &i32) -> String {
let a = match *i {
0 => "NUL",
1 => "SOH",
2 => "STX",
// ...
125 => "}",
126 => "~",
127 => "DEL",
_ => "",
}
a
}
首先,您不需要返回
字符串
,一个&'static str
就足够了。其次,您可以简单地设置一个包含所有您喜欢的代码表示的&'static str
数组,并使用.get()
获取相关的字符串片段,只要您的所有字符代码都是连续的(如果我有ASCII权限,它们应该是连续的)。即使它们不是,也可以在空白处放置空字符串
代码应如下所示:
const CHARS: [&'static str; 128] = ["NUL", "SOH", "STX", .., "DEL"];
fn get_char_code(c: i32) -> &'static str {
CHARS.get(c as usize).unwrap_or("")
}
您可以使用
格式代码>宏,用于将字符
转换为字符串
:
fn to_ascii(i: &i32) -> String {
match *i {
x@0...127 => format!("{:?}", x as u8 as char),
_ => "".into(),
}
}
fn main() {
for x in 0x09..0x12 {
print!("{} ", to_ascii(&x));
}
println!("");
//'\t' '\n' '\u{b}' '\u{c}' '\r' '\u{e}' '\u{f}' '\u{10}' '\u{11}'
for x in 0x30..0x40 {
print!("{} ", to_ascii(&x));
}
println!("");
//'0' '1' '2' '3' '4' '5' '6' '7' '8' '9' ':' ';' '<' '=' '>' '?'
}
对于更类似生锈的方式,您可以使用智能指针作为返回类型:
use std::borrow::Cow;
fn to_ascii(i: &i32) -> Cow<'static, str> {
match *i {
x@0...32 => ["NUL", "SOH", "STX", ..., "SPC"][x as usize].into(),
x@32...126 => format!("{}", x as u8 as char).into(),
127 => "DEL".into(),
_ => "".into(),
}
}
使用std::borrow::Cow;
fn to_ascii(i:&i32)->Cow无论它值多少钱,我都不会介意匹配
版本。唯一的调整是不需要临时变量。我鼓励您遵循并返回一个&'static str
,如果需要,您的调用者可以将其转换为字符串
:
fn get_char_code(i: &i32) -> &'static str {
match *i {
0 => "NUL",
1 => "SOH",
2 => "STX",
// ...
125 => "}",
126 => "~",
127 => "DEL",
_ => "",
}
}
此外,我强烈建议不要在代码中使用“ASCII”一词。大多数程序员将“ASCII字符”关联为映射到特定字符、标点符号或控制代码的单个u8
数据。您可以按如下方式转换:
println!("{}", 'A' as i8); // prints 65
println!("{}", 65 as char); // prints 'A'
您可以将u32
与以下各项一起使用,而不是i32
:
使用std::char::from_u32;
fn main()->结果{
设n=0x21;
设c=从uu32(n)开始,好吗?;
println!(“{}”,c);
好(())
}
谢谢,我想既然ascii值永远不会改变,我最好使用&'static str
这将如何为0(或任何其他多字符映射)返回“NUL”
println!("{}", 'A' as i8); // prints 65
println!("{}", 65 as char); // prints 'A'