A Deeper Look at the std::string Class

Replacing All Substrings in a String

What's the best approach to replace all occurrences of a substring within a std::string?

Abstract art representing computer programming

Replacing all occurrences of a substring within a std::string is a common operation in text processing. While C++ doesn't have a built-in replace_all() function, we can implement one efficiently. Here's a robust approach:

#include <iostream>
#include <string>

std::string replace_all(
  std::string str,
  const std::string& from,
  const std::string& to
) {
  size_t start_pos{0};
  while (
    (start_pos = str.find(from, start_pos))
    != std::string::npos
  ) {
    str.replace(start_pos, from.length(), to);

    // In case 'to' contains 'from', like
    // replacing 'x' with 'yx'
    start_pos += to.length();
  }
  return str;
}

int main() {
  std::string text{
    "The quick brown fox jumps over the lazy dog"};
  std::string from{"o"};
  std::string to{"0"};

  std::cout << "Original: " << text << '\n';
  std::cout << "Replaced: "
    << replace_all(text, from, to) << '\n';

  // Another example
  text = "Hello, Hello, Hello!";
  from = "Hello";
  to = "Hi";
  std::cout << "Original: " << text << '\n';
  std::cout << "Replaced: "
    << replace_all(text, from, to) << '\n';
}
Original: The quick brown fox jumps over the lazy dog
Replaced: The quick br0wn f0x jumps 0ver the lazy d0g
Original: Hello, Hello, Hello!
Replaced: Hi, Hi, Hi!

Let's break down the replace_all() function:

  1. We use std::string::find() to locate each occurrence of the from substring.
  2. We replace each occurrence using std::string::replace().
  3. We update start_pos to continue searching after the replaced substring.

This approach is efficient because:

  • It modifies the string in-place, avoiding unnecessary allocations.
  • It handles cases where the replacement string contains the search string.
  • It uses std::string's built-in methods, which are typically optimized.

For more complex pattern matching and replacing, you might consider using regular expressions:

#include <regex>

std::string regex_replace_all(
  const std::string& str,
  const std::string& from,
  const std::string& to
) {
  return std::regex_replace(
    str, std::regex(from), to
  );
}

However, be aware that regex operations can be slower for simple replacements. Use them when you need more complex pattern matching capabilities.

For very large strings or performance-critical code, you might want to consider using a more sophisticated string searching algorithm like Boyer-Moore or Knuth-Morris-Pratt. These can be more efficient for long strings or when doing many replacements.

Remember, the most appropriate method depends on your specific use case, including the size of your strings, the complexity of your patterns, and your performance requirements.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved