C++ .replace()

Christine_Yang's avatar
Published Jun 3, 2022Updated Dec 21, 2022
Contribute to Docs

The .replace() method returns a string with a portion replaced by another string, or a portion of another string.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
    • Beginner Friendly.
      11 hours

Syntax

baseString.replace(pos, len, str, subpos, sublen)
  • baseString is the string whose contents are being replaced.
  • pos is the zero-based starting position of the replacement.
  • len is the number of characters to be replaced.
  • str is the replacement string.
  • subpos is optional, and is the zero-based starting point of the replacement characters used from str.
  • sublen is optional, and is the number of replacement characters used from str.

If subpos and sublen aren’t specified, the entire str is used for the replacement.

Codebyte Example

The following example replaces a portion of a base string with a portion of another string:

Code
Output

All contributors

Contribute to Docs

Learn C++ on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
    • Beginner Friendly.
      11 hours