Conversion of strtr php function in C#

与世无争的帅哥 提交于 2019-12-22 10:29:39

问题


Need to convert this php code in C#

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

Does an equivalent C# function exist?


回答1:


The PHP method strtr() is translate method and not string replace method. If you want to do the same in C# then use following:

As per your comments

string input = "baab";
var output = input.Replace("a", "0").Replace("b","1");

Note : There is no exactly similar method like strtr() in C#.

You can find more about String.Replace method here




回答2:


   string input ="baab";
   string strfrom="ab";
   string strTo="01";
   for(int i=0; i< strfrom.Length;i++)
   {
     input = input.Replace(strfrom[i], strTo[i]);
   }
   //you get 1001

sample method:

string StringTranslate(string input, string frm, string to)
{
      for(int i=0; i< frm.Length;i++)
       {
         input = input.Replace(frm[i], to[i]);
       }
      return input;
}



回答3:


The horrors wonders of PHP...I got confused by your comments, so looked it up in the manual. Your form replaces individual characters (all "b"'s get to be "1", all "a"'s get to be "0"). There's no direct equivalent in C#, but simply replacing twice will get the job done:

string result = input.Replace('+', '-').Replace('/', '_')



回答4:


@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


来源:https://stackoverflow.com/questions/33474491/conversion-of-strtr-php-function-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!