Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

rust
communitycreator

What is the string.find() method in Rust?

okwudili onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

In Rust, the find() method is used to find the first match of a specified character or another string. It returns the byte index of the first character of the specified character or string in the case of a successful match, and None in case of an unsuccessful match.

Syntax

string.find(match)
Syntax for find() method in Rust

Parameters

This method takes two parameters:

  • match: This is the string or character searched for in a string,
  • string: This is the string in which the method searches for match.

Return value

This method returns the byte index of the first character of the match. For example: Some(2), Some(14). For no match, it returns None.

Example

fn main() {
// create some strings
let str1 = "Educative is the best platform!";
let str2 = "Rust";
let str3 = "Welcome to Edpresso";
let str4 = "Programming";
// create the matches
let match1 = "is";
let match2 = 'R';
let match3 = "to";
let match4 = "23";
// find the matches and print byte indices
println!(" {:?}", str1.find(match1));
println!(" {:?}", str2.find(match2));
println!(" {:?}", str3.find(match3));
println!(" {:?}", str4.find(match4));
}
Using find() to get the byte index of the first character of a match in Rust

Explanation

  • Lines 3–6: We create some strings.
  • Lines 9–12: We create some more strings that we will search for in the strings created in lines 3–6.
  • Lines 15–18: We use the find() method to check if any matches were found and print the results to the console screen.

RELATED TAGS

rust
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring