これはあなたが望むものですか?
"This will be a test".Replace("i", "X").Replace("t", String.Empty)
これは関数の簡単な実装です-文字列に含まれていて非常に乱雑なCHRTRAN
場合は機能しません。\0
ループを使用してより良いものを作成することもできますが、私はLINQを使用してそれを試してみたかっただけです。
public static String ChrTran(String input, String source, String destination)
{
return source.Aggregate(
input,
(current, symbol) => current.Replace(
symbol,
destination.ElementAtOrDefault(source.IndexOf(symbol))),
preResult => preResult.Replace("\0", String.Empty));
}
そして、あなたはそれを使うことができます。
// Returns "ThXs wXll be a es"
String output = ChrTran("This will be a test", "it", "X");
クリーンなソリューションを提供するためだけに、LINQがなくても同じで、\0
ケースでもStringBuilder
機能します。もちろん、入力を変更することはありませんが、使用しているため、ほぼ適切です。
public static String ChrTran(String input, String source, String destination)
{
StringBuilder result = new StringBuilder(input);
Int32 minLength = Math.Min(source.Length, destination.Length);
for (Int32 i = 0; i < minLength; i++)
{
result.Replace(source[i], destination[i]);
}
for (Int32 i = minLength; i < searchPattern.Length; i++)
{
result.Replace(source[i].ToString(), String.Empty);
}
return result.ToString();
}
ヌル参照処理がありません。
tvanfossonのソリューションに触発されて、私はLINQにセカンドショットを与えました。
public static String ChrTran(String input, String source, String destination)
{
return new String(input.
Where(symbol =>
!source.Contains(symbol) ||
source.IndexOf(symbol) < destination.Length).
Select(symbol =>
source.Contains(symbol)
? destination[source.IndexOf(symbol)]
: symbol).
ToArray());
}