Rust

contains

if

fn main() {
*// Part 1: use find as indexof.*
let value = *"_xy_xy"*;
if let Some(result) = value.find(*"xy"*) {
println!(*"INDEXOF: {result}"*);
}
*// Part 2: get substring based on index.*
let animals = *"cat and dog"*;
if let Some(result) = animals.find(*"do"*) {
if let Some(inner) = animals.get(result..) {
println!(*"SUBSTRING AT DO: {inner}"*);
}
}
}INDEXOF: 1
SUBSTRING AT DO: dog

Option

fn main() {
let value = *"aa"*;
*// Version 1: if no result is found, find returns None.*
let result = value.find(*"zz"*);
if result == None {
println!(*"Returned None"*);
}
*// Version 2: use Some to test, and then get the actual result.*
let result2 = value.find(*"a"*);
if let Some(m) = &result2 {
println!(*"{}"*, m);
}
}Returned None
0

fn main() {
let value = *"_xy_xy"*;
*// Use rfind to search from the right.*
let result = value.rfind(*"xy"*).unwrap();
println!(*"RFIND: {}"*, result);
}RFIND: 4

Substring

fn main() {
let value = *"abc123"*;
*// Find index of first digit.*
let result = value.find(|c: char| c.is_ascii_digit()).unwrap();
*// Take substring of remaining chars.*
let numbers = value.get(result..).unwrap();
*// Print results.*
println!(*"FIRST DIGIT: {}"*, result);
println!(*"FIRST DIGIT START: {}"*, numbers);
}FIRST DIGIT: 3
FIRST DIGIT START: 123

vec

position

fn main() {
let v = vec![10, 25, 30];
*// Use find on an iter() to search a vector for a matching element.*
if let Some(result) = v.iter().find(|&&x| x >= 20) {
println!(*"Greater than or equal to 20: {result}"*);
}
}Greater than or equal to 20: 25

Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.

Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.

This page was last updated on Nov 22, 2023 (edit).