a concise shot of dev knowledge
Become a Contributor
Concise shots of dev knowledge

RELATED TAGS

rust
communitycreator

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

okwudili onyejiaku

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
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time

Copyright ©2022 Educative, Inc. All rights reserved.

soc2