@@ -2090,6 +2090,67 @@ impl String {
20902090 unsafe { self . as_mut_vec ( ) } . splice ( ( start, end) , replace_with. bytes ( ) ) ;
20912091 }
20922092
2093+ /// Replaces the leftmost occurrence of a pattern with another string, in-place.
2094+ ///
2095+ /// This method can be preferred over [`string = string.replacen(..., 1);`][replacen],
2096+ /// as it can use the `String`'s existing capacity to prevent a reallocation if
2097+ /// sufficient space is available.
2098+ ///
2099+ /// # Examples
2100+ ///
2101+ /// Basic usage:
2102+ ///
2103+ /// ```
2104+ /// #![feature(string_replace_in_place)]
2105+ ///
2106+ /// let mut s = String::from("Test Results: ❌❌❌");
2107+ ///
2108+ /// // Replace the leftmost ❌ with a ✅
2109+ /// s.replace_first('❌', "✅");
2110+ /// assert_eq!(s, "Test Results: ✅❌❌");
2111+ /// ```
2112+ ///
2113+ /// [replacen]: ../../std/primitive.str.html#method.replacen
2114+ #[ cfg( not( no_global_oom_handling) ) ]
2115+ #[ unstable( feature = "string_replace_in_place" , issue = "147949" ) ]
2116+ pub fn replace_first < P : Pattern > ( & mut self , from : P , to : & str ) {
2117+ let range = match self . match_indices ( from) . next ( ) {
2118+ Some ( ( start, match_str) ) => start..start + match_str. len ( ) ,
2119+ None => return ,
2120+ } ;
2121+
2122+ self . replace_range ( range, to) ;
2123+ }
2124+
2125+ /// Replaces the rightmost occurrence of a pattern with another string, in-place.
2126+ ///
2127+ /// # Examples
2128+ ///
2129+ /// Basic usage:
2130+ ///
2131+ /// ```
2132+ /// #![feature(string_replace_in_place)]
2133+ ///
2134+ /// let mut s = String::from("Test Results: ❌❌❌");
2135+ ///
2136+ /// // Replace the rightmost ❌ with a ✅
2137+ /// s.replace_last('❌', "✅");
2138+ /// assert_eq!(s, "Test Results: ❌❌✅");
2139+ /// ```
2140+ #[ cfg( not( no_global_oom_handling) ) ]
2141+ #[ unstable( feature = "string_replace_in_place" , issue = "147949" ) ]
2142+ pub fn replace_last < P : Pattern > ( & mut self , from : P , to : & str )
2143+ where
2144+ for < ' a > P :: Searcher < ' a > : core:: str:: pattern:: ReverseSearcher < ' a > ,
2145+ {
2146+ let range = match self . rmatch_indices ( from) . next ( ) {
2147+ Some ( ( start, match_str) ) => start..start + match_str. len ( ) ,
2148+ None => return ,
2149+ } ;
2150+
2151+ self . replace_range ( range, to) ;
2152+ }
2153+
20932154 /// Converts this `String` into a <code>[Box]<[str]></code>.
20942155 ///
20952156 /// Before doing the conversion, this method discards excess capacity like [`shrink_to_fit`].
0 commit comments