In Rust, converting a string to a character vector is achieved by using the .chars() method on the string. This method returns an iterator that yields each character of the string sequentially. If you want to collect these characters into a vector, you can use the .collect::<Vec<char>>() method.
Here is a specific example:
rustfn main() { let s = "Hello, world!"; let char_list: Vec<char> = s.chars().collect(); println!("{:?}", char_list); }
In this example:
- We first define a string
s. - We use the
.chars()method to obtain the character iterator fors. - We collect these characters into a
Vec<char>vector using the.collect()method. - Finally, we print out this character vector, which will display as
['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!'].
This approach is particularly useful for scenarios where you need to operate on each character of the string. For example, you might need to filter, transform, or perform other operations on the characters. By first converting the string to a character vector, these operations become more straightforward.
2024年7月1日 12:52 回复