需要在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/