Skip to content

[API Proposal]: Add string.ReplaceWhere for predicate-based replacement and removal #130295

Description

@yousefyahia828

Background and motivation

Background and Motivation

string provides Replace overloads for replacing known values, but there is no built-in API for replacing or removing characters based on a predicate.

This is a common operation that currently requires manual iteration or LINQ. A dedicated API would improve readability while allowing for an efficient implementation.

API Proposal

Proposed API

namespace System;

public partial class String
{
    /// <summary>
    /// Replaces or removes all characters that satisfy the specified predicate.
    /// </summary>
    /// <param name="predicate">
    /// A function that determines whether a character should be replaced.
    /// </param>
    /// <param name="replacement">
    /// The replacement character. If <see langword="null"/>, matching characters are removed.
    /// </param>
    /// <returns>
    /// A new string with matching characters replaced or removed.
    /// </returns>
    public string ReplaceWhere(
        Func<char, bool> predicate,
        char? replacement = null);
}

API Usage

API Usage

string value = "abc123";

value.ReplaceWhere(char.IsDigit);
// "abc"

value.ReplaceWhere(char.IsDigit, '*');
// "abc***"

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.RuntimeuntriagedNew issue has not been triaged by the area owner

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions