I have a string with the value "Program", and I want to find the index of character 'g' in that string.
The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.
Strings are ordered sequences of character data, 00:15 and the individual characters of a string can be accessed directly using that numerical index. String indexing in Python is zero-based, so the very first character in the string would have an index of 0 , 00:30 and the next would be 1 , and so on.
Overview. The length of a string is the number of characters that make up that string. We can get the length of a string in Rust using the len() method.
Although a little more convoluted than I would like, another solution is to use the Chars
iterator and its position()
function:
"Program".chars().position(|c| c == 'g').unwrap()
find
used in the accepted solution returns the byte offset and not necessarily the index of the character. It works fine with basic ASCII strings, such as the one in the question, and while it will return a value when used with multi-byte Unicode strings, treating the resulting value as a character index will cause problems.
This works:
let my_string = "Program";
let g_index = my_string.find("g"); // 3
let g: String = my_string.chars().skip(g_index).take(1).collect();
assert_eq!("g", g); // g is "g"
This does not work:
let my_string = "プログラマーズ";
let g_index = my_string.find("グ"); // 6
let g: String = my_string.chars().skip(g_index).take(1).collect();
assert_eq!("グ", g); // g is "ズ"
You are looking for the find
method for String. To find the index of 'g'
in "Program"
you can do
"Program".find('g')
Docs on find.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With