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

Time:12-04

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);
}

CodePudding user response:

You can use slices for this, specifically &str slices. Note the &.

These links might be helpful:

fn main() {
    let s = "elephant";
    let mid = s.len() / 2;

    let sliced = &s[mid - 1..mid   1];
    println!("{}", sliced);
}

CodePudding user response:

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