2012-04-16 33 views
2

我正在寻找数组匹配方法。将数组与另一个数组匹配

这里我有两个数组的代码显示

char[] normalText = new char[26] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; 
char[] parsedText = new char[26] {'b', 'c', 'd', 'e', 'f', 'g', ...}; 

和,我想与它们匹配的话,如果我写的程序就会变成“BCD” “ABC”和我”犯了一个文本解析器方法是这样的:

 parsing = input.ToCharArray(); 
     foreach (char c in parsing) 
     { 
      throw new NotImplementedException(); 
     } 

但是,我不知道我应该做的是什么样的查询的foreach语句后与它们匹配。如果你知道如何在代码中匹配这个,请在​​这里发帖,这将是非常令人愉快的

+0

你有两个名为'normalText'的数组? – 2012-04-16 12:17:42

+0

这是“家庭作业”吗? – cfedermann 2012-04-16 12:18:05

+1

你想检查它们是否相等,或者你想查看其中一个是否是另一个的子集? – 2012-04-16 12:18:18

回答

0

这是你想要的。您可以使用Array.IndexOf(oldText, s)获取旧数组中的字符索引,然后通过该索引获取新数组中的值。

string input="abc"; 
char[] oldText = new char[26] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; 
char[] newText = new char[26] { 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z','a'}; 

char[] array = input.ToCharArray(); 
StringBuilder output= new StringBuilder(); 
foreach(char s in array) 
{ 
    output.Append(newText[Array.IndexOf(oldText, s)]); 
} 

Console.WriteLine(output.ToString()); // "bcd" 
2

我会使用这样的:

var input = "abc"; 
var parsing = input.ToCharArray(); 
var result = new StringBuilder(); 
var offset = (int)'a'; 
foreach (var c in parsing) { 
    var x = c - offset; 
    result.Append(parsedText[x]); 
} 
1

它看起来像你想用这些来使一个1:1的翻译。

最好的(即:最具扩展性的)的方式来做到这一点可能是一个字典:

Dictionary<char, char> dictionary = new Dictionary<char, char>(); 
dictionary.Add('a', 'b'); 
dictionary.Add('b', 'c'); 
dictionary.Add('c', 'd'); 
//... etc (can do this programmatically, also 

则:

char newValue = dictionary['a']; 
Console.WriteLine(newValue.ToString()); // "b" 

等。使用字典,您还可以获得列表的所有功能,根据您正在做的事情,这可以非常方便。

0

就像这样,现在将其格式化为最适合您的方式。

char[] normalText = new char[26] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; 
char[] dictionary = new char[26] {'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y' };  

parsing = input.ToCharArray(); 
foreach (char c in parsing) 
     { 
      if(index(c,normalText)<= dictionary.Length) 
       Console.WriteLine(dictionary[index(c,normalText)]); 
     } 

int index(char lookFor, char[] lookIn) 
    { 
     for (int i = 0; i < lookIn.Length; i++) 
      { 
       if (lookIn[i] == lookFor) 
        return i; 
      } 
     return -1; 
    } 
相关问题