这是你想要的吗?
"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 的情况下也一样,并且也适用于这些案例,并且由于使用 a但不会修改输入,\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());
}