Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace the first occurrence of a pattern in a String

Tags:

string

rust

I am trying to write a replace_first() function but I could not find the correct way to manage this.

I have the following input:

let input = "Life is Life".to_string();

I want to replace such input to following romantic output:

My wife is Life

The replace function replaces all the occurrences. How can I implement the replace_first function so I can use it like following:

let input = "Life is Life".to_string();
let output = input.replace_first("Life", "My wife");
println!({}, output); // Expecting the output as "My wife is life"
like image 597
Akiner Alkan Avatar asked Jan 26 '23 19:01

Akiner Alkan


1 Answers

Use replacen

Replaces first N matches of a pattern with another string.

replacen creates a new String, and copies the data from this string slice into it. While doing so, it attempts to find matches of a pattern. If it finds any, it replaces them with the replacement string slice at most count times.

let input = "Life is Life".to_string();
let output = input.replacen("Life", "My wife", 1);

assert_eq!("My wife is Life", output);

Rust Playground

like image 177
ponury-kostek Avatar answered Feb 07 '23 17:02

ponury-kostek