How to replace the first occurrence of a substring in a string with Rust

1 Answer

0 votes
fn replace_first(input: &str, search: &str, replace: &str) -> String {
    if let Some(pos) = input.find(search) {
        let mut result = String::new();
        result.push_str(&input[..pos]); // before match
        result.push_str(replace);       // replacement
        result.push_str(&input[pos + search.len()..]); // after match
        result
    } else {
        input.to_string()
    }
}

fn main() {
    let s = "aa bb cc dd ee cc";
    
    let result = replace_first(s, "cc", "YY");
    
    println!("{}", result);
}



    
/*
run:

aa bb YY dd ee cc
   
*/

 



answered Jul 20, 2025 by avibootz
...