To find the kth index of a character in a string in Rust, you can use the char_indices()
method of the str
type to get an iterator that returns each character and its corresponding index in the string. You can then use the nth()
method of the iterator to get the element at the kth index.
Here's an example implementation:
main.rs245 chars11 lines
This function takes the input string, the index k, and the character you want to search for as parameters. It then loops over pairs of indices and characters in the string using char_indices()
, checks if the character at the current index matches the character you're searching for, and if so, checks if the current index matches k.
If there are no matches, the function returns None
.
You can call this function like this:
main.rs92 chars4 lines
This will find the index of the third occurrence of the letter "l" in the string "hello world", which is 3.
gistlibby LogSnag