我需要从套接字解析输入流。 数据是从Telnet客户端发送的,因此我想通过查找流中的第一个'\r'
字符来处理传入的字符串,然后在返回字符前选择字节,最后处理任何字符。解析Ascii字符的传入TCP流,处理退格符char
在这里处理'\b'
位的惯用方法是什么? 我目前正在使用一个可变堆栈并将字符推送到它上面,如果有退格,我弹出最后一个字符。 然后只需将结果转换为字符串。
但我觉得可能有一些很好的方式来做到这一点与模式匹配和尾递归。那么,这怎么可以做到F#的方式呢?
let receiveInput (inputBuffer:StringBuilder) (received:Tcp.Received)=
let text = Encoding.ASCII.GetString(received.Data.ToArray());
inputBuffer.Append(text) |> ignore
let all = inputBuffer.ToString()
match all.IndexOf('\r') with
| enter when enter >= 0 ->
let textToProcess = all.Substring(0,enter)
inputBuffer.Remove(0,enter+2) |> ignore
//this is the part I'm wondering about
let stack = new Stack<char>()
for c in textToProcess do
if c = '\b' then stack.Pop() |> ignore
else stack.Push c
let input = new System.String(stack |> Seq.rev |> Seq.toArray)
Some(input)
| _ ->
None
啊是的,它应该折叠不减少,没有意识到在f# –
@RyanWGough'reduce'类似于'fold',但它输入为空时崩溃。 –
谢谢,真棒,这正是我正在寻找的。 –