小编Sas*_*nov的帖子

切片包含Unicode字符的字符串

我有一段文字,字符长度不同.

let text = "Hello ??????";
Run Code Online (Sandbox Code Playgroud)

给定开始(包含)和结束(排除)字符索引时,我需要获取一小段字符串.我试过这个

let slice = &text[start..end];
Run Code Online (Sandbox Code Playgroud)

并得到以下错误

thread 'main' panicked at 'byte index 7 is not a char boundary; it is inside '?' (bytes 6..8) of `Hello ??????`'
Run Code Online (Sandbox Code Playgroud)

我想这是因为西里尔字母是多字节的,并且[..]符号使用字节索引来表示字符.如果我想使用字符索引切片,我可以使用什么,就像我在Python中做的那样:

slice = text[start:end]

我知道我可以使用chars()迭代器并手动遍历所需的子字符串,但是有更简洁的方法吗?

string unicode slice rust

18
推荐指数
2
解决办法
1539
查看次数

标签 统计

rust ×1

slice ×1

string ×1

unicode ×1