Back to Blog
C#

C# String Replace: Syntax, Overloads, and Performance

c# string replace: Learn how to use C# string Replace effectively, including overloads, case sensitivity, performance tradeoffs, and when to use Regex or StringBuilder.

string manipulationC# methodsRegexStringBuilderperformance
Illustration of C# string replace operation showing substring substitution

c# string replace requires a clear understanding of the core syntax, runtime behavior, and practical implementation patterns demonstrated in the examples below.

The string.Replace method in C# is the simplest way to replace all occurrences of a character or substring with another. It has two overloads: one that replaces characters, and one that replaces strings.

string text = "Hello, World!"; string replaced = text.Replace("World", "C#"); // replaced == "Hello, C#!"

The character overload works similarly but only replaces single characters.

Replacing All Occurrences vs. First Occurrence

Unlike some other languages, Replace replaces every occurrence of the search string, not just the first. If you need to replace only the first occurrence, you must implement that logic yourself, for example using IndexOf and Substring.

string text = "one two one three"; int index = text.IndexOf("one"); string firstReplaced = index >= 0 ? text.Substring(0, index) + "1" + text.Substring(index + "one".Length) : text;

This approach is straightforward but becomes error-prone if you need to replace multiple distinct first occurrences. For those cases, consider a StringBuilder loop.

Case Sensitivity and Culture

Replace performs an ordinal, case-sensitive, and culture-insensitive comparison. That means it treats "abc" and "ABC" as different. If you need case-insensitive replacement, there is no built-in overload that accepts StringComparison. You'll need to use Regex.Replace with RegexOptions.IgnoreCase or write a custom loop.

using System.Text.RegularExpressions; string text = "Hello hello HELLO"; string result = Regex.Replace(text, "hello", "hi", RegexOptions.IgnoreCase);

This replaces all case variants of "hello" with "hi". The regex approach is the most direct way to achieve case-insensitive replacement without altering the original casing of the replacement string.

Using StringComparison with Replace

Since Replace doesn't accept a StringComparison parameter, many developers assume it's missing. You can work around this by using Regex.Replace or by converting both strings to a common case before replacement, but that changes the original case of the replacement. The safest approach is to use Regex when you need culture-aware or case-insensitive matching.

For example, converting both sides to lowercase and then replacing works only if the replacement is also lowercase, which is rarely acceptable. The regex solution preserves the replacement exactly as written.

Performance Considerations

Because strings are immutable, Replace creates a new string every time it's called. For a single replacement, this is fine. But if you're doing many replacements in a loop, you'll allocate many intermediate strings, which can hurt performance. In such cases, consider using StringBuilder with its Replace method, which modifies the builder in place and avoids extra allocations.

var sb = new StringBuilder("Hello, World!"); sb.Replace("World", "C#"); string result = sb.ToString();

The StringBuilder.Replace method has the same all-occurrence behavior and case sensitivity as string.Replace, but it operates on the existing buffer. This is especially beneficial when you perform several replacements on the same text before converting to a final string.

Alternatives: Regex.Replace and StringBuilder

Regex.Replace is the right tool when you need pattern matching, case-insensitive replacement, or complex transformations. It's more flexible but also slower due to regex parsing and matching overhead. StringBuilder.Replace is useful for repeated replacements on the same buffer. The table summarizes the tradeoffs:

ApproachUse whenPerformance
string.ReplaceSimple, all-occurrence replacementFast for one-off, allocates new string
StringBuilder.ReplaceMany replacements on same bufferIn-place, fewer allocations
Regex.ReplacePattern-based or case-insensitiveSlower, but flexible

For a one-time replacement, string.Replace is clear and efficient. For a loop that modifies a growing string, StringBuilder avoids the quadratic cost of repeated string concatenation. For pattern matching, regex is the only practical choice.

Common Pitfalls and Edge Cases

Be aware that Replace throws ArgumentNullException if the search string is null. An empty search string is allowed but results in the replacement being inserted between every character, which is rarely what you want. Also, replacement does not handle overlapping matches; it scans left to right and replaces non-overlapping occurrences.

string text = "aaa"; string result = text.Replace("aa", "b"); // result is "ba" because the first two 'a' are replaced, then the third remains.

This behavior is consistent with most replace implementations, but it's worth remembering when you're working with patterns that could overlap.

Practical Example: Replacing Placeholders in a Template

A common use case is replacing placeholders in a template string. Here's a simple example:

string template = "Hello {name}, welcome to {company}!"; string result = template.Replace("{name}", "Alice").Replace("{company}", "Contoso");

This works because Replace returns a new string, so you can chain calls. However, if you have many placeholders, a StringBuilder or a loop with Regex might be more maintainable.

For a small, fixed set of placeholders, chaining Replace calls is readable and efficient. For a dynamic set, consider a dictionary and a loop:

var replacements = new Dictionary<string, string> { ["{name}"] = "Alice", ["{company}"] = "Contoso" }; string result = template; foreach (var kvp in replacements) { result = result.Replace(kvp.Key, kvp.Value); }

This approach scales better and keeps the replacement logic in one place, especially when the placeholder list comes from configuration or user input.

c# string replace: Practical Usage and Code Examples | RYUSLOG DEV