Homam
Homam

Reputation: 23871

Is there a way in C# to replace a collection of characters with another collection respectively?

Is there a way in C# to replace a collection of characters with another collection respectively as the following:

"ABCDEF.KindOfReplace( "AE", "12"); // the result: "1BCD2F"

Upvotes: 1

Views: 146

Answers (3)

rene
rene

Reputation: 42483

There is no such function out of the box. If you handcraft something this might be one of many possible solutions. It manipulates a char array and uses IndexOfAny to find the chars to replace.

public static string KindOfReplace( this string src, string find, string repl)
{
    char[] target = src.ToCharArray();
    char[] findChars = find.ToCharArray();
    int finder = src.IndexOfAny(findChars);
    while(finder>-1)
    {
        int charFind = find.IndexOf(src[finder]);
        target[finder] = repl[charFind];
        finder = src.IndexOfAny(findChars, finder+1);
    }
    return new String(target);
}   

Upvotes: 0

Daniel Kelley
Daniel Kelley

Reputation: 7747

No there isn't but it seems to me your code is equivalent to:

var myString = "ABCDEF";
var newString = myString.Replace("A", "1").Replace("E", "2");

You could probably write an extension method to make this nicer, but for large replacement arrays it wouldn't be particularly efficient.

EDIT:

As pointed out in the comments below you could use a StringBuilder in the cases where you have a large number of strings/chars to replace.

Upvotes: 3

driis
driis

Reputation: 164331

No, not directly. You would have to built it yourself using the string primitives, or Regex.

A simple implementation could be:

public static string KindOfReplace(this string original, string charsToReplace, string replacements)
{
    var replacementDic = charsToReplace.Select((ch,i) => new { ch, i }).ToDictionary(x => x.ch, x => replacements[x.i]);
    var result = original.Select(ch => replacementDic.ContainsKey(ch) ? replacementDic[ch] :ch);
    return new String(result.ToArray());
}

(Above is an example, remember to add guards for same length strings, etc).

Upvotes: 1

Related Questions