How to process the backspace terminal control character in Java? [closed]

本小妞迷上赌 提交于 2019-12-13 09:53:54

问题


I am coding a basic telnet server in Java and I would like to process the backspace terminal control character denoted by '\b'. The backspace character deletes/removes the preceding character in the string.

I am currently using the example method below to successfully achieve this but does anyone know of a cleaner/more efficient method?

Many thanks for any assistance you can provide.

/*
Example input: 
"This is a dog\b\b\bcat"
"\b\b\bThis is x\b a cat"
"\b\b\bThis\b\b\bThis is a dog\b\b\bcat"
*/

    private String processBackspace(String input)
    {
        StringBuilder output = new StringBuilder();
        int backSpaceCount = 0, index = 0;
        boolean isBackSpace = false;

        for (int i = input.length() - 1; i >= 0; i--)
        {
            char c = input.charAt(i);
            if (c == '\b')
            {
                isBackSpace = true;
                backSpaceCount++;
            }
            else
                isBackSpace = false;

            if (!isBackSpace)
            {
                index = i - backSpaceCount; 
                if (index >= 0)
                    output.append(input.charAt(index));
            }
        }           
        output.reverse();
        return output.toString();
    }

回答1:


I would do it like this

private String processBackspace(String input) {
    StringBuilder sb = new StringBuilder();
    for (char c : input.toCharArray()) {
        if (c == '\b') {
            if (sb.length() > 0) {
                sb.deleteCharAt(sb.length() - 1);
            }
        } else {
            sb.append(c);
        }
    }
    return sb.toString();
}


来源:https://stackoverflow.com/questions/16381879/how-to-process-the-backspace-terminal-control-character-in-java

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