pub fn str_to_range_unchecked(string: &str, substring: &str) -> Range<usize>
Expand description

Get the start and end (byte index) range (Range<usize>), where substring is located in string. The returned range is relative to string.

If substring is not a part of string, it either panics or returns an invalid range.

For a safe version, check out str_to_range().

Panics

Panics if substring is not a substring of string. *

* Panicking depends on where the strings are located in memory. It might not panic but instead return an invalid range.

Example

let string = "Foo Bar Baz";

let substring = &string[4..7]; // "Bar"

assert_eq!(str_to_range_unchecked(string, substring), 4..7);

Example - Substring of Substring

Since the resulting range is relative to string, that implies substring can be a substring of a substring of a substring of … and so on.

let s1 = "Foo Bar Baz";

// Substring of `s1`
let s2 = &s1[4..11]; // "Bar Baz"

// Substring of `s1`
let s3 = &s1[4..7]; // "Bar"

// Substring of `s2`, which is a substring of `s1`
let s4 = &s2[0..3]; // "Bar"

// Get the range of `s2` relative to `s1`
assert_eq!(str_to_range_unchecked(s1, s2), 4..11);

// Get the range of `s3` relative to `s1`
assert_eq!(str_to_range_unchecked(s1, s3), 4..7);

// Get the range of `s4` relative to `s1`
assert_eq!(str_to_range_unchecked(s1, s4), 4..7);

// Get the range of `s4` relative to `s2`
assert_eq!(str_to_range_unchecked(s2, s4), 0..3);