Question

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();
    }
Was it helpful?

Solution

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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top