我正在开发Rust中的词法分析器/记号赋予器,它需要将UTF-8输入文件(以&[u8]形式给出)解析成单独的char进行解析,但还必须跟踪文件中的字节位置。在稍后的阶段--比如在输入中需要报告错误时--我需要根据字节和回溯来定位有问题的字符,以找到其行上的相对位置。
将字节流解析为字符(跟踪字节位置)的惯用方法是什么?标准库中有没有函数可以让我计算出后面有多少个尾随字节,或者一个字节是前导字节还是尾字节,或者我必须根据Unicode标准自己实现这些函数?
例如,如下所示:
// First to parse some input stream:
let input: &[u8] = "something";
for (chr, bytepos) in parse(input) {
// ...
}
// Later to locate a character based on the byte position and
// use is_leading_byte() to step backwards and count the number
// of characters since the start of the line:
let chr: u8 = input[some_bytepos];
chr.is_leading_byte();
chr.is_trailing_byte();发布于 2016-11-04 15:31:32
看起来char_indices解决了我的两个问题:
let input: &str = "something";
for (offset, chr) in input.char_indices() {
// ...
}在以后的阶段,可以使用split_at来查找字符并倒着计数该行中前面的字符的数量
let input: &str = "something";
let where: usize = 4;
let (left,_) = input.split_at(where);
for (offset, chr) in left.char_indices().rev() {
if chr == '\n' {
break;
}
// ...
}Matthieu M.指出一个警告:迭代和计算Unicode代码点并不一定对应于人们本能地认为是单个字母的脚本;这是由于多个代码点可以组成一个字素的事实。An example can be found in the documentation of chars()。
https://stackoverflow.com/questions/40410805
复制相似问题