乐闻世界logo
搜索文章和话题

How do I convert a string to a list of chars in Rust?

1个答案

1

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:

rust
fn main() { let s = "Hello, world!"; let char_list: Vec<char> = s.chars().collect(); println!("{:?}", char_list); }

In this example:

  1. We first define a string s.
  2. We use the .chars() method to obtain the character iterator for s.
  3. We collect these characters into a Vec<char> vector using the .collect() method.
  4. 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 回复

你的答案