CodeBlanks Logo Icon CodeBlanks

contains and replace

Search with contains and replace with replace.

contains and replace

Methods for searching and replacing in text:

let m = "kedi ve kedi yavrusu";
m.contains("ve")            // true
m.starts_with("kedi")       // true
m.ends_with("su")           // true
m.find("yavru")             // Some(13): byte position
m.replace("kedi", "köpek")  // a new String
m.replacen("kedi", "at", 1) // only the first: "at ve kedi yavrusu"

replace returns a new String; the original text doesn't change.

Char and closure patterns

These methods accept not only text but also a char or a closure:

let s = "a1b2c3";
println!("{}", s.contains(char::is_numeric));       // true
println!("{:?}", s.find(|c: char| c.is_ascii_digit()));   // Some(1)
println!("{}", s.replace(|c: char| c.is_numeric(), "")); // abc
println!("{}", "--x--".trim_matches('-'));          // x

Practice Search and replace

For let metin = "kedi ve kedi yavrusu";, print the results of contains("ve"), find("yavru") ({:?}) and replace("kedi", "köpek") on one line separated by spaces.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn main() {
    let metin = "kedi ve kedi yavrusu";
    println!("{} {:?} {}", metin.contains("ve"), metin.find("yavru"), metin.replace("kedi", "köpek"));
}

Expected output

true Some(13) köpek ve köpek yavrusu

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is <code>"Rust".contains("rust")</code>?

  • Compile error
  • false Correct answer
  • true
  • Some(0)

Explanation: Searching is case-sensitive. For a case-insensitive search, convert both sides with to_lowercase().

2 Replace all

Question
let m = "kedi ve kedi";
let y = m.____("kedi", "at");   // "at ve at"
Answer
let m = "kedi ve kedi";
let y = m.replace("kedi", "at");   // "at ve at"

Explanation: replace changes every match; replacen only the first n.

3 Expression and result on "kedi ve kedi"

Term Meaning
contains("ve") true
find("ve") Some(5)
replacen("kedi", "at", 1) "at ve kedi"
starts_with("ve") false

All lessons in Beginner