この php コードを C# に変換する必要があります
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
あなたのソリューションが置換を実行している間、phpstrtr
は入力配列の文字を同時に置換し、結果は別のものを実行するために使用されると思います。だから私は次の変更を加えました:
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
PHP
メソッドstrtr()
は変換メソッドであり、メソッドではありませんstring replace
。同じことをしたい場合は、C#
次を使用します。
皆さんのコメント通り
string input = "baab";
var output = input.Replace("a", "0").Replace("b","1");
strtr()
注: のようにまったく同じ方法はありませんC#
。
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;
}
PHPの恐ろしさ・・・あなたのコメントに戸惑ったので、マニュアルで調べてみました。フォームは個々の文字を置き換えます (すべての "b" は "1" になり、すべての "a" は "0" になります)。C# には直接同等のものはありませんが、単純に 2 回置き換えるだけで作業が完了します。
string result = input.Replace('+', '-').Replace('/', '_')