Question: After executing the code, I get Some('H') . How to get a single character string correctly?

Code:

 fn main(){ let strr="Hello"; println!("{:?}",strr.chars().nth(0)); } 

Running: https://play.rust-lang.org/?gist=dc781ddb6e6d3441125a2f6a8d7162e6&version=stable

  • 3
    Still add .nth(0).unwrap() ? - VTT
  • The example code does not match the question title: you are trying to iterate over the characters in a string and get some one in a row. Indexing lines is effectively done by built-in indexing operators over a range, but the output is line segments and you need to be careful with indexes, otherwise you can “cut” the UTF-8 code sequence and get panic. See also the char_indices() method. - mzabaluev
  • I agree with you "String indexing is effectively done by built-in indexing operators on a range,". He found the worst way to get the index of a string. By code, this is a whole cycle ... fn nth (& mut self, mut n: usize) -> Option <Self :: Item> {for x in self {if n == 0 {return Some (x)} n - = 1 ; } None} - Denis Kotlyarov
  • Bo is Iter and without a loop you cannot get a certain Iter position. - Denis Kotlyarov

2 answers 2

 fn main(){ let strr="Hello"; println!("{:?}",strr.chars().nth(0)); } 

"After compiling and running, I get Some ('H'). How to get (just an index without extraneous characters) H without Some ()?"

I generally lose weight from such issues. Information:

Option is an analogue of null , its safe version. Ie if the index 0 in the string does not exist will return None , and if the index exists, then there will be Some('') . Option itself is enum having either Some or None .

Chars nth method https://doc.rust-lang.org/std/str/struct.Chars.html

 fn nth(&mut self, n: usize) -> Option<Self::Item>[src] //ВОЗВРАТ OPTION Returns the nth element of the iterator. 

How to handle Option ??

 fn main() { let test_str = "Hello"; let mut test_chars = test_str.chars(); if let Some(a) = test_chars.nth(0) { //ЕСЛИ ФУНКЦИЯ ВЕРНУЛА OPTION::SOME(A) то println!("{:?}", a); } //НО НЕ ПРОВЕРЯЕТСЯ ЕСЛИ ИНДЕКСА 0 В СТРОКЕ НЕ СУЩЕСТВУЕТ } 

Running: https://play.rust-lang.org/?gist=d543bbf77e8ad87976246753bedd69df&version=stable

 fn main() { let test_str = "Hello"; let mut test_chars = test_str.chars(); match test_chars.nth(0) { Some(a) => { println!("{:?}", a); }, None => { println!("Индекса 0 в строке test не существует. Спасибо за внимание."); } } //Этот пример мне нравится больше, в нем вы можете реагировать на отсутствие индекса, или на его присутствие. И намного лучше еслиб вы в прошлом примере писали else к if. } 

Running: https://play.rust-lang.org/?gist=586bac28433d519d5771269441a351de&version=stable

Bad example:

 fn main() { let test_str = "Hello"; let mut test_chars = test_str.chars(); let char_a = test_chars.nth(0).unwrap(); println!("{:?}", char_a); } 

Running: https://play.rust-lang.org/?gist=c87388771277e5337ded6d38c56fdee6&version=stable

Describe the response to the absence of an index better than using unwrap. Unwrap says if you returned Some (a) then write 'a' to a variable, and if index 0 does not exist, then abort the program.

Tip: Do not use the NTH method for such purposes as getting a string index. Bear in mind that it works for a slightly different purpose.

 fn nth(&mut self, mut n: usize) -> Option<Self::Item> { for x in self { if n == 0 { return Some(x) } n -= 1; } None } 

For such purposes it is well suited: (but it returns exactly str)

 fn main() { let strr="Hello"; if let Some(a) = strr.get(0..1){ println!("{:?}", a); } } 

Running: https://play.rust-lang.org/?gist=dc781ddb6e6d3441125a2f6a8d7162e6&version=stable

    The nth() method of the Iterator type returns Option , because the iteration, in general, can end before the specified element is reached. If you are sure that there is a value, you can get it from Option using the unwrap() or expect() methods:

     fn main(){ let strr = "Hello"; let iter = strr.chars(); let c = iter.nth(0).expect("leading character not present"); }