Need to convert this php code in C#
strtr($input, '+/', '-_')
Does an equivalent C# function exist?
@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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With