我有telnet
文本通信的缓冲方法。除了标准字母,这个通信有一些有趣的控制字符。其中一个是带有8
整数值的字符DELETE。
我想实现这个值 - 它真的可以帮助我使用telnet中的程序,因为目前我需要重新输入整个命令,如果我按下一个字符错误。
所以我创建了一个每次收到字符时调用的检查函数:
public boolean newChar(char current, StringBuilder all) {
//Debug info
switch (current) {
case 13 : Log.debug("Character '\\r' [13]");break;
case 10 : Log.debug("Character '\\n' [10]");break;
case 8 : Log.debug("Character DELETE [8]");break;
default:Log.debug("Character '"+current+"' ["+(int)current+"]");
}
//Delete character
if(current==8) {
int length = all.length();
if(length>1) {
///THIS DOES NOT WORK
//all.delete(length-2, length-1);
///WHILE FOLLOWING WORKS WELL
all.deleteCharAt(length-1);
all.deleteCharAt(length-2);
Log.debug("Deleted one character from buffer. Current buffer:\n "+all);
}
else
all.deleteCharAt(length-1);
}
//Ignore newlines
else if(current=='\r'||current=='\n') {
all.deleteCharAt(all.length()-1);
}
//Return true if current character is newline
//True return value means that the buffer now contains whole message...
return current=='\n';
}
如果收到删除字符,则应删除该字符以及其前面的字符。我认为delete(int start, int end)
应该适合这个目的。
int length = builder.length();
builder.delete(length-2, length-1);
但是,这会删除2个字符和 删除字符 - 共3个字符:
Character '6' [54]
Character '6' [54]
Character '6' [54]
Character DELETE [8]
Deleted one character from buffer. Current buffer:
6
我也试过builder.delete(length-1, length);
,虽然没有意义。我没有删除任何我能看到的东西。 (我猜它删除了删除字符然后默默地失败了。)
有趣的是,这对我来说很好:
builder.deleteCharAt(length-1);
builder.deleteCharAt(length-2);
有人可以解释为什么会这样吗?