The JavaScript String charCodeAt() function returns the Unicode value of the character at the specified index in a string. The index is zero-based, meaning the first character in the string has an index of 0, the second character has an index of 1, and so on. The returned value is an integer between 0 and 65535, representing the Unicode value of the character. If the specified index is out of range, the function returns NaN (Not a Number). This function is useful for working with non-ASCII characters and for performing string manipulation tasks that require knowledge of the Unicode values of characters. Keep reading below to learn how to Javascript String charCodeAt in Rust.

Looking to get a head start on your next software interview? Pickup a copy of the best book to prepare: Cracking The Coding Interview!

Buy Now On Amazon

Javascript String charCodeAt in Rust With Example Code

JavaScript’s `charCodeAt()` method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index. Rust provides a similar method for strings called `as_bytes()`, which returns a byte slice of the string’s UTF-8 encoded bytes. We can then use Rust’s indexing syntax to access the byte at the given index and convert it to an integer.

Here’s an example implementation of `charCodeAt()` in Rust:


fn char_code_at(s: &str, index: usize) -> Option {
s.as_bytes().get(index).map(|b| *b as u32)
}

This function takes a string slice `s` and an index `index`, and returns an `Option` representing the UTF-8 code unit at the given index. If the index is out of bounds, it returns `None`.

To use this function, simply call it with a string and an index:


let s = "hello";
let index = 1;
let char_code = char_code_at(s, index);
println!("The char code at index {} is {:?}", index, char_code);

This will output:


The char code at index 1 is Some(101)

Note that the `charCodeAt()` method in JavaScript returns `NaN` if the index is out of bounds. In Rust, we chose to return an `Option` instead to make it explicit that the result may be `None`.

Equivalent of Javascript String charCodeAt in Rust

In conclusion, the Rust programming language provides a powerful and efficient alternative to Javascript’s String charCodeAt function. The Rust equivalent function, char_indices(), allows developers to easily access the Unicode code points of individual characters in a string. This functionality is particularly useful for tasks such as string manipulation, text processing, and data analysis. With Rust’s focus on performance and safety, developers can trust that their code will run smoothly and reliably. Overall, the char_indices() function is a valuable tool for any Rust developer working with strings and text data.

Contact Us