In Rust, strings are UTF-8 encoded, which means that each character (i.e. Unicode scalar value) can be represented by one or more bytes. Therefore, a byte index does not necessarily correspond to a character boundary or to the nth character in the string.
If you're sure the given byte index is on a character boundary (you can check this with the is_char_boundary method), one common method to convert a byte index into a character index (i.e. the position in terms of characters) is to count the number of characters preceding that byte index.
Here are two approaches:
1. Slicing and Counting
If byte_index is valid (i.e. it's on a character boundary), you can slice the string up to that byte index and count the characters:
fn byte_to_char_index(s: &str, byte_index: usize) -> Option<usize> {
if s.is_char_boundary(byte_index) {
Some(s[..byte_index].chars().count())
} else {
None // Not on a char boundary
}
}
fn main() {
let s = "नमस्ते"; // "Hello" in Hindi (UTF-8, multibyte characters)
let byte_index = 6; // You need to ensure this is a valid char boundary
match byte_to_char_index(s, byte_index) {
Some(char_index) => println!("Character index: {}", char_index),
None => println!("Byte index {} is not a valid character boundary.", byte_index),
}
}
In this example, s[..byte_index].chars().count() counts how many characters are in the substring from the start of s up to byte_index. That count is essentially the character index corresponding to byte_index.
2. Using char_indices
Alternatively, you can iterate over the character indices and use the position method:
fn byte_to_char_index(s: &str, byte_index: usize) -> Option<usize> {
s.char_indices().position(|(i, _)| i == byte_index)
}
fn main() {
let s = "नमस्ते";
let byte_index = 6; // Ensure this is a valid char boundary
match byte_to_char_index(s, byte_index) {
Some(char_index) => println!("Character index: {}", char_index),
None => println!("Byte index {} is not a valid character boundary.", byte_index),
}
}
Here, s.char_indices() returns an iterator of (byte_index, character) pairs. The position method finds the first occurrence where the byte index in the tuple equals the provided byte_index—this position is the character index.
Important Note
Both methods assume that byte_index is a valid character boundary. You can check this with:
if s.is_char_boundary(byte_index) {
// safe to proceed
} else {
// handle error
}
If byte_index falls in the middle of a multi-byte character, slicing (s[..byte_index]) will panic at runtime.
Summary
- Use
s[..byte_index].chars().count() if you are sure that byte_index is a valid character boundary.
- Alternatively, use
s.char_indices().position(|(i, _)| i == byte_index) which returns an Option<usize> that is None if byte_index is not a character boundary.
Both methods effectively convert a byte index to a character index in Rust.