Java backspace escape

我与影子孤独终老i 提交于 2019-12-17 18:54:42

问题


I just tested the backspace escape as follows:

System.out.println("Hello\b");

I expected to get the output: Hell
But it was: "Hello" with a square block

anyone knows how java handle this?


回答1:


Java doesn't 'handle' that character at all. All it knows about is a byte stream onto which the OS says it can write bytes, and it will happily write bytes into it, including an ASCII backspace.

What happens when the stream receives that character has nothing whatsoever to do with Java, it is totally terminal-dependent. Some terminals will erase the previous character, some will display the backspace character as some weird glyph, or even as a special "backspace character" glyph. Some may drop the character altogether if they can't interpret it, others (most terminal emulators, in fact) will behave differently depending on how they're configured. But all this has nothing to do with Java, they will behave that way whether they're written to by Java or Perl print or C++ cout or whatever else.




回答2:


To get your desired Output i.e. Hell you need to add a space character after \b. Because \b will only move the cursor (virtually) to 1 position backward but it won't delete it. All you can do is replace the character to be deleted by space. Thus try the following line to get Hell as output :

System.out.println("Hello\b ");

PS : This Solution works on Windows OS and Ubuntu OS. For other OS it may behave differently as explained by @Kilian Foth above.




回答3:


It should work perfectly fine in Windows command console. This bug is recognizeable as an Eclipse bug: bug 76936. Also see How to get backspace \b to work in Eclipse’s console?




回答4:


Try to use terminal to execute your class file.

 java classname

When IDE execute \b, it will automatically ignore it. Because there is no corresponding library in IDE to run \b. However, if you run them in terminal, it could be executed. All the terminals have that library.




回答5:


You might want to write a function to do it:

def static public String backspace (String str){
    return str.substring(0,str.length-1)
}



回答6:


you are using System.out.println("...") which is essentially System.out.print("...\n")

Don't use .println, you are just removing the newline ...



来源:https://stackoverflow.com/questions/3328824/java-backspace-escape

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!