Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of strtr php function in C#

Need to convert this php code in C#

strtr($input, '+/', '-_')

Does an equivalent C# function exist?

like image 269
Roberto Mattea Avatar asked Dec 18 '22 22:12

Roberto Mattea


1 Answers

@Damith @Rahul Nikate @Willem van Rumpt

Your solutions generally work. There are particular cases with different result:

echo strtr("hi all, I said hello","ah","ha");

returns

ai hll, I shid aello

while your code:

ai all, I said aello

I think that the php strtr replaces the chars in the input array at the same time, while your solutions perform a replacement then the result is used to perform another one. So i made the following modifications:

   private string MyStrTr(string source, string frm, string to)
    {
        char[] input = source.ToCharArray();
        bool[] replaced = new bool[input.Length];

       for (int j = 0; j < input.Length; j++)
            replaced[j] = false;

        for (int i = 0; i < frm.Length; i++)
        {
            for(int j = 0; j<input.Length;j++)
                if (replaced[j] == false && input[j]==frm[i])
                {
                    input[j] = to[i];
                    replaced[j] = true;
                }
        }
        return new string(input);
    }

So the code

MyStrTr("hi all, I said hello", "ah", "ha");

reports the same result as php:

ai hll, I shid aello
like image 190
Roberto Mattea Avatar answered Dec 21 '22 10:12

Roberto Mattea