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

Overview

In Rust, we can replace the content of a string with the replace() method. This method replaces a specified match with another string.

Syntax

This widget is not supported in dev-mode. Kindly enable it or run using yarn webapp:dev-widgets.

Parameters

  • string: This is the string whose substring we want to replace.

  • match: This is the match we want to find and replace.

  • substring: This is the replacement for the match we find.

Return value

This method returns a new string with every match replaced. If no match is found, the string remains the same.

Code example

This widget is not supported in dev-mode. Kindly enable it or run using yarn webapp:dev-widgets.

Explanation

  • Lines 2–5: We create some strings.

  • Lines 8–11: We replace some sub-strings of the strings we created using the replace() method. Then, we print the results to the console.

Output

  • For first example: the word better is replaced by best at every occurrence.

  • For second example: boring is replaced by interesting.

  • For the third and fourth examples: there wasn’t any match so the string is returned as it was.

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved