Using the string type in use std::string::{String};
type, how can I access a character at index “i”?
For example,
public fun get_char(text: &String): String {
text:: ...
...
}
I want to get the second character of the string text
Using the string type in use std::string::{String};
type, how can I access a character at index “i”?
For example,
public fun get_char(text: &String): String {
text:: ...
...
}
I want to get the second character of the string text
The answer to this question is complicatd because std::string::String
holds UTF8 strings, and so the meaning of the word “character” is overloaded and ambiguous.
It’s possible to access an individual code unit (byte) by using std::string::bytes
to get a reference to the underlying bytes of the string, and then calling std::vector::borrow
on that:
public fun code_unit(text: &string::String, off: u64): u8 {
*vector::borrow(string::bytes(text), off)
}
but what appears as a single grapheme on screen may be composed of multiple code points, which could themselves be multiple code units (bytes), and the standard library does not offer a way to generally iterate through code points or graphemes – you will have to build that on top of the bytes
primitive.
The story is much simpler if you are using std::ascii::String
, because there a single character is represented by a single code point, which is represented by a single code unit, which is a byte. In that case, you could implement:
public fun get_char(text: &ascii::String, off: u64): ascii::String {
let char = *vector::borrow(ascii::as_bytes(text), off);
ascii::string(vector[char])
}