1

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

0

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, i was getting confused as i had been using .chars().nth(index).unwrap() to get one letter, then i tried slices but thought if i was specifying two values a start and end i had to use [start,end] syntax as opposed to [start..end] i have it working now
1

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]

4 Comments

Those aren't the same. The former yields the indexth codepoint. The latter yields the slice of bytes at the range given.
The confusion here likely resides in the fact that your question is (unintentionally) underspecified. Namely, you use the word "letter" a few times without actually defining it. The word "letter" is an abstraction, and there are multiple different valid implementations of it depending on what you're doing.
I just meant it worked because it allowed me to display the correct Char to the screen, in the odd case the middle char, in the even case the middle 2 chars.
There is no problem with the second solution if all the characters are single-byte encoded, like ASCII. It will become much more complicated when dealing with characters of multi-byte encodings. For example, '中' in Chinese needs three bytes to represent in UTF-8. "中".chars().count() returns 1 while "中".len() returns 3. So, you need to make sure if encoding is a factor to consider for your case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.