如何在 Rust 中将字符串切片为 utf8

问题描述 投票:0回答:1

我正在编写一个 rust 玩具解析器,我想在字符串输入中处理 UTF-8 字符。我知道我需要使用

chars
方法来获取 UTF-8 迭代器以正确获取 UTF-8 字符,但我想使用 UTF-8 索引对字符串进行切片。有什么方法我可以使用吗?我研究了 SWC,但我无法理解它如何处理 UTF-8 字符串,因为输入 api 似乎需要开发自身来处理正确的 UFT-8 索引。

use swc_common::input::{StringInput, Input};
use swc_common::BytePos;
fn main() {
    let utf8_str = "中文字串";
    let mut input =  StringInput::new("中文字串", BytePos(0), BytePos(utf8_str.len().try_into().unwrap()));
    println!("{:?}", input.slice(BytePos(0), BytePos(3)));
    println!("{:?}", &utf8_str[0..3]);
   // is there any function like slice(start_usize, end_usize) can get utf-8 string 
}

string rust utf-8
1个回答
1
投票

不支持使用字符索引进行切片,并且由于

SliceIndex
特征已被密封,因此您无法实现它。但是您可以使用
char_indices
来计算每个 utf8 字符对应的字节索引:

fn main() {
    let utf8_str = "中文字串";
    let start_char = 1;
    let end_char = 2;
    let mut indices = utf8_str.char_indices().map(|(i, _)| i);
    let start = indices.nth(start_char).unwrap();
    let end = indices.nth(end_char - start_char - 1).unwrap_or(utf8_str.len());
    println!("{:?}", &utf8_str[start..end]);
}

输出:

"文"
© www.soinside.com 2019 - 2024. All rights reserved.