c# - C#中strtr php函数的转换

标签 c# php asp.net replace strtr

需要在C#中转换此php代码

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

是否存在等效的 C# 函数?

最佳答案

@Damith @Rahul Nikate @Willem van Rumpt

您的解决方案通常有效。有不同结果的特殊情况:

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

返回

ai hll, I shid aello

当你的代码:

ai all, I said aello

我认为 php strtr 同时替换了输入数组中的字符,而您的解决方案执行替换然后结果用于执行另一个。 所以我做了以下修改:

   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);
    }

所以代码

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

报告与 php 相同的结果:

ai hll, I shid aello

关于c# - C#中strtr php函数的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33474491/

相关文章:

c# - 从 C# Windows 应用程序创建 .exe

c# - 在数组中获取 9 个不同数字的算法

c# - 如何将现有内存缓冲区包装为 GDI 的 DC

c# - 如何检测字符串是否为C#中的货币

php - 无法在多维数组中声明新数组

asp.net - 更新 .aspx 页面

c# - EnableViewState 会影响 GridView 上的哪些控件?

javascript - 依赖/级联下拉菜单

php - Joomla:为什么 "Extension Manager"菜单项没有显示在 "Extensions"下拉菜单中?

asp.net - 是否可以将 40 个字符的 SHA1 哈希转换为 20 个字符的 SHA1 哈希?