How to get a substring of a &str based on character index?

Viewed 65

I am trying to write a program that takes a list of words and then, if the word has an even length, prints the two middle letters. If the word has an odd length, it prints the single middle letter.

I can find the index of the middle letter(s), but I do not know how to use that index to print the corresponding letters of the word.

fn middle(wds: &[&str)){
   for word in wds{
      let index = words.chars().count() /2;
      match words.chars().count() % 2{
          0 => println!("Even word found"),
          _ => println!("odd word found")
      }
   }

}

fn main(){

  let wordlist = ["Some","Words","to","test","testing","elephant","absolute"];
  middle(&wordlist);
}

2 Answers

Hey after posting i found two different ways of doing it, the fact i had two seperate ways in my head was confusing me and stopping me finding the exact answer.

//i fixed printing the middle letter of the odd numbered string with
word.chars().nth(index).unwrap()

//to fix the even index problem i did
&word[index-1..index+1]
Related