如何从包含图形表示的字符串中获取字符(A-Z)? 例如,如果我使用 3x5 字母,字母“A”的图形表示将是:
#
# #
###
# #
# #
这个是“E”的:
###
#
###
#
###
我可以继续这样做,但它看起来不正确!
switch (input)
//Case 1 belongs to character A
case " # \n# #\n###\n# #\n# #\n":
{
return 'A';
}
case "###\n# \n###\n# \n###\n":
{
return 'E';
}
//till question mark
default: return '?';
有没有算法或一些 ASCII 艺术技巧可以使用 java 来做到这一点?
最佳答案
即使您不需要双向映射,我也会使用 Map
以可读的方式存储字母:
public class Letters {
public String getLetter(String graphicalLetter) {
return letters.get(graphicalLetter);
}
private static final Map<String, String> letters = new HashMap<String, String>();
static {
// @formatter:off
letters.put(
" # \n" +
"# #\n" +
"###\n" +
"# #\n" +
"# #\n"
, "A");
letters.put(
...
, "E");
// @formatter:on
}
}
这样,图形表示就全部集中在一个位置,并且不会困惑代码的任何其他部分,同时仍然可供人眼读取。
您可以创建一个算法,例如首先查看总体中#
的数量,然后查看第一列或第一行中的哈希数并找到该字母这样,但这可能会过于复杂并且难以阅读/理解。
为了进一步提高可读性,您甚至可以考虑从 map 条目中删除 \n
并在 getLetter
方法中自动删除它们。
关于java - 从图形表示中获取字母 (A-Z),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51232391/