Function line_span::str_to_range

source ·
pub fn str_to_range(string: &str, substring: &str) -> Option<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.

Returns Some if substring is a part of string, otherwise None.

For an unchecked version, check out str_to_range_unchecked().

Example

let string1 = "Foo Bar Baz";
let string2 = "Hello World";

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

// Returns `Some` as `substring` is a part of `string1`
assert_eq!(str_to_range(string1, substring), Some(4..7));

// Returns `None` as `substring` is not a part of `string2`
assert_eq!(str_to_range(string2, substring), None);

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(s1, s2), Some(4..11));

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

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

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