需要在C#中转换这个php代码
strtr($input, '+/', '-_')是否存在一个等价的C#函数?
发布于 2015-11-02 09:35:19
PHP方法strtr()是平移方法,而不是string replace方法。如果要在C#中执行同样的操作,请使用以下命令:
根据你的意见
string input = "baab";
var output = input.Replace("a", "0").Replace("b","1");注意:在
strtr()中没有完全类似于C#的方法。
发布于 2015-11-02 11:29:45
@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发布于 2015-11-02 09:34:04
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抽样方法:
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;
}https://stackoverflow.com/questions/33474491
复制相似问题