Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all occurrences of a string (in array) with a single value

Tags:

string

c#

.net

I have a string array:

string[] arr2 = { "/", "@", "&" };

I have another string (i.e. strValue). Is there a clean way to replace all instances of the array contents with a single value (i.e. an underscore)? So before:

strValue = "a/ new string, with some@ values&"

And after:

strValue = "a_ new string, with some_ values_"

I considered doing this:

strValue = strValue.Replace("/", "_");
strValue = strValue.Replace("@", "_");
strValue = strValue.Replace("&", "_");

But my array of characters to replace may become a lot bigger.

like image 926
Andyww Avatar asked Nov 15 '16 14:11

Andyww


People also ask

How do you replace all occurrences in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.

How do you replace multiple elements in an array?

splice() method lets you replace multiple elements in an array with one, two, or however many elements you like. Just use the syntax: . splice(startingIndex, numDeletions, replacement1, replacement2, ... )

Can you replace values in an array?

Replace an Element in an Array using Array.Use the indexOf() method to get the index of the element you want to replace. Call the Array. splice() method to replace the element at the specific index. The array element will get replaced in place.

What do the replaceAll () do?

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match.


3 Answers

Instead of using the Replace over and over you could just write your own. This might even be a performance gain since you mentioned

But my array may get a lot bigger.

public string Replace(string original, char replacement, params char[] replaceables)
{
    StringBuilder builder = new StringBuilder(original.Length);
    HashSet<char> replaceable = new HashSet<char>(replaceables);
    foreach(Char character in original)
    {
        if (replaceable.Contains(character))
            builder.Append(replacement);
        else
            builder.Append(character);
    }
    return builder.ToString();
}

public string Replace(string original, char replacement, string replaceables)
{
    return Replace(original, replacement, replaceables.ToCharArray());
}

Can be called like this:

Debug.WriteLine(Replace("a/ new string, with some@ values&", '_', '/', '@', '&'));
Debug.WriteLine(Replace("a/ new string, with some@ values&", '_', new[] { '/', '@', '&' }));
Debug.WriteLine(Replace("a/ new string, with some@ values&", '_', existingArray));
Debug.WriteLine(Replace("a/ new string, with some@ values&", '_',"/@&"));

Output:

a_ new string, with some_ values_
a_ new string, with some_ values_
a_ new string, with some_ values_
a_ new string, with some_ values_

As @Sebi pointed out, this would also work as an extension method:

public static class StringExtensions
{
    public static string Replace(this string original, char replacement, params char[] replaceables)
    {
        StringBuilder builder = new StringBuilder(original.Length);
        HashSet<Char> replaceable = new HashSet<char>(replaceables);
        foreach (Char character in original)
        {
            if (replaceable.Contains(character))
                builder.Append(replacement);
            else
                builder.Append(character);
        }
        return builder.ToString();
    }

    public static string Replace(this string original, char replacement, string replaceables)
    {
        return Replace(original, replacement, replaceables.ToCharArray());
    }
}

Usage:

"a/ new string, with some@ values&".Replace('_', '/', '@', '&');
existingString.Replace('_', new[] { '/', '@', '&' });
// etc.
like image 178
Manfred Radlwimmer Avatar answered Sep 24 '22 11:09

Manfred Radlwimmer


This is how i'd do it building a regex clause from the list of delimiters and replacing them with an underscore

string[] delimiters = { "/", "@", "&" };
string clause = $"[{string.Join("]|[", delimiters)}]";
string strValue = "a/ new string, with some@ values&";
Regex chrsToReplace = new Regex(clause);
string output = chrsToReplace.Replace(strValue, "_");

You'll probably want to encapsulate within if(delimiters.Any()), else it will crash if the array is empty

like image 33
Innat3 Avatar answered Sep 26 '22 11:09

Innat3


Sure. Here's one approach:

var newString = arr2.Aggregate(strValue, (net, curr) => net.Replace(curr, "_"));

If you're only substituting individual characters and have large enough input sizes to need optimization, you can create a set from which to substitute:

var substitutions = new HashSet<char>() { '/', '@', '&' };
var strValue = "a/ new string, with some@ values&";
var newString = new string(strValue.Select(c => substitutions.Contains(c) ? '_' : c).ToArray());
like image 43
Asad Saeeduddin Avatar answered Sep 26 '22 11:09

Asad Saeeduddin