你有一个想法如何简化这个简单的“翻译机制”?如何简化这段代码?
是一个哈希表有用吗?
char translateChar(char strIn)
{
char strOut = '?';
if (strIn == 'A') strOut = '1';
else if (strIn == 'B') strOut = '2';
else if (strIn == 'C') strOut = '3';
else if (strIn == 'D') strOut = '4';
else if (strIn == 'E') strOut = '5';
else if (strIn == 'F') strOut = '6';
else if (strIn == 'G') strOut = '7';
else if (strIn == 'H') strOut = '8';
else if (strIn == 'I') strOut = '9';
else if (strIn == 'J') strOut = '@';
else if (strIn == 'K') strOut = 'A';
else if (strIn == 'L') strOut = 'B';
else if (strIn == 'M') strOut = 'C';
else if (strIn == 'N') strOut = 'D';
else if (strIn == 'O') strOut = 'E';
else if (strIn == 'P') strOut = 'F';
else if (strIn == 'Q') strOut = 'G';
else if (strIn == 'R') strOut = 'H';
else if (strIn == 'S') strOut = 'I';
else if (strIn == 'T') strOut = 'J';
else if (strIn == 'U') strOut = 'K';
else if (strIn == 'V') strOut = 'L';
else if (strIn == 'W') strOut = 'M';
else if (strIn == 'X') strOut = 'N';
else if (strIn == 'Y') strOut = 'O';
else if (strIn == 'Z') strOut = 'P';
else if (strIn == '2') strOut = 'X';
else if (strIn == '1') strOut = 'Y';
else if (strIn == '_') strOut = '_';
return strOut;
}
字典是有用这里肯定。 – 2011-12-21 13:35:44
就我所知,散列表肯定会完成这项工作,但会为您节省一些代码字符。另一方面,每个字符都必须在散列表中进行搜索。这意味着这种方法可能不太干净,但更好的性能(如果你用返回'x'替换strOut ='x'),因为这会取消任何进一步的检查。 – 2011-12-21 13:39:19
http://codereview.stackexchange.com/ – 2011-12-21 14:01:06