数组将匹配值替换为另一个数组值。 C#

时间:2014-03-12 03:13:59

标签: c# arrays replace enumerator

如何使用相应的数组枚举器值字符串替换数组中的项目。

string a = "12345"; //Check if exists.
string[] b = a.Select(x => x.ToString()).ToArray();

string c = "54321"; // Replacement values.
string[] d = c.Select(y => y.ToString()).ToArray();

string e = "0A9B8C7D6E5F4G3H2I1"; // String to amend.
string[] f = e.Select(z => z.ToString()).ToArray();

foreach (string num in b)
{
    replace = f.Select(x => x.Replace(b //Current b enumerator, d //enumerator = b current)).ToArray()

 }
// Output Replace = "0A9B8C7D6E1F2G3H4I5";

2 个答案:

答案 0 :(得分:1)

澄清问题,您想应用替代密码。

替换密码只是用不同的字母或符号替换每个字母或符号。这是Julius Caesar使用的经典加密方法。作为此想法的变体,您可以将原始字母加密为一组完全不同的符号。

一种简单的方法是使用Linq。它不是很可读,但是可以完成工作:

var a = "12345"; // original chars
var c = "54321"; // replacement chars
var e = "0A9B8C7D6E5F4G3H2I1"; // source string
var r = String.Concat(e.Select(x=>a.Contains(x)?c[a.IndexOf(x)]:x));

结果字符串r为:

r == "0A9B8C7D6E1F2G3H4I5"

记住要包含在标题中

using System.Linq; 

答案 1 :(得分:0)

以下内容如何:

var a = "12345";
var c = "54321";
var e = "0A9B8C7D6E5F4G3H2I1";

// create a mutable copy of e
var builder = new StringBuilder(e);
for (var i = 0; i < e.Length; ++i) // for each character position in e
{
    // look for that character in a
    var index = a.IndexOf(e[i]);
    // if we found it, replace the character at that position with the
    // corresponding character from c
    if (index >= 0) { builder[i] = c[index]; }
}
var result = builder.ToString(); // 0A9B8C7D6E1F2G3H4I5