Hone logo
Hone
Problems

Managing Ownership with Borrowing in Rust

Rust's ownership system is central to its memory safety guarantees. This challenge focuses on understanding and utilizing borrowing – a key mechanism for accessing data without transferring ownership. You'll implement a function that processes a string slice, demonstrating how to borrow data effectively and safely.

Problem Description

You are tasked with creating a function called count_vowels that takes a string slice (&str) as input and returns the number of vowels (a, e, i, o, u, case-insensitive) present in the string. The function must use borrowing; it should not take ownership of the input string. This is crucial to avoid unnecessary copying and to allow the original string to remain usable after the function call. The function should handle empty strings gracefully.

Examples

Example 1:

Input: "Hello, World!"
Output: 3
Explanation: The string contains 'e', 'o', and 'o', which are vowels.

Example 2:

Input: "Rust is awesome"
Output: 7
Explanation: The string contains 'u', 'i', 'a', 'o', 'e', and two 'o's.

Example 3:

Input: ""
Output: 0
Explanation: An empty string contains no vowels.

Example 4:

Input: "AEIOUaeiou"
Output: 10
Explanation: All characters are vowels, both uppercase and lowercase.

Constraints

  • The input string will consist of ASCII characters.
  • The function must not take ownership of the input string. Using &str is mandatory.
  • The function must be case-insensitive when counting vowels.
  • The function should be efficient; avoid unnecessary allocations.

Notes

  • Remember that borrowing allows you to access data without transferring ownership.
  • String slices (&str) are references to a portion of a string.
  • Consider using iterators to efficiently traverse the string.
  • The to_lowercase() method on strings can be helpful for case-insensitive comparisons.
  • Think about how to handle edge cases like empty strings. A simple return 0; at the beginning can be a good starting point.
  • Focus on demonstrating your understanding of borrowing principles. The solution should be concise and readable.
Loading editor...
rust