在这里做什么我有点不知所措.我希望某些键击序列执行某些操作.
我基本上需要存储最后N次击键,当按下某个键时,查找与最近的击键相匹配的序列.
所以说我有2个序列:
yes no
当我输入时,我的击键历史如下所示:
a ab abc abcn abcno
此时它应识别序列号并执行适当的操作.
它还需要使用以下序列:
year yell
和输入如:
yeayell
密钥序列具有有限长度,因此可以使用类似循环缓冲区的东西丢弃旧的击键,在这种情况下,最佳大小为3.
我的击键用Keys枚号表示.
我应该使用哪些数据结构或算法来存储最后N次击键并在最后找到序列?
解决方法
这是一个概念验证,允许您使用任何字符序列集合.我假设你只匹配字符(而不是其他键,如Keys.Left).
// Initialize the collection of strings to be matched against here. string[] stringSequences = new string[] { "yes","no","hello" }; int maxLength = stringSequences.Max(s => s.Length); // The buffer to hold the sequence of the last N characters. string buffer = ""; while (true) { // Read the next character,and append it to the end of the buffer. ConsoleKeyInfo next = Console.ReadKey(); buffer += next.KeyChar; // If the buffer has exceeded our maximum length,// trim characters from its start. if (buffer.Length > maxLength) buffer = buffer.Substring(1); // Check whether the last n characters of the buffer // correspond to any of the sequences. string match = stringSequences.FirstOrDefault(s => buffer.EndsWith(s)); if (match != null) { // Match! Perform any custom processing here. Console.WriteLine(Environment.NewLine + "Match: " + match); } }
编辑:适合使用键.
我无法轻易测试Keys,所以我使用的是ConsoleKey;但是,翻译代码应该不会太难.
// Initialize the collection of key sequences to be matched against here. ConsoleKey[][] keysSequences = new ConsoleKey[][] { new ConsoleKey[] { ConsoleKey.Y,ConsoleKey.E,ConsoleKey.S },new ConsoleKey[] { ConsoleKey.N,ConsoleKey.O },new ConsoleKey[] { ConsoleKey.H,ConsoleKey.L,}; int maxLength = keysSequences.Max(ks => ks.Length); // The buffer to hold the sequence of the last N keys. List<ConsoleKey> buffer = new List<ConsoleKey>(); while (true) { // Read the next key,and append it to the end of the buffer. ConsoleKeyInfo next = Console.ReadKey(); buffer.Add(next.Key); // If the buffer has exceeded our maximum length,// trim keys from its start. if (buffer.Count > maxLength) buffer.RemoveAt(0); // Check whether the last n keys of the buffer // correspond to any of the sequences. ConsoleKey[] match = keysSequences.FirstOrDefault(ks => buffer.Skip(buffer.Count - ks.Length).SequenceEqual(ks)); if (match != null) { // Match! Perform any custom processing here. Console.WriteLine(Environment.NewLine + "Match: " + string.Concat(match.Select(k => k.ToString()).ToArray())); } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。